Home > Backend Development > PHP Tutorial > Detailed explanation of using regular expressions to group strings

Detailed explanation of using regular expressions to group strings

巴扎黑
Release: 2023-03-16 10:24:01
Original
1618 people have browsed it

这篇文章主要给大家介绍了关于利用正则表达式将字符串分组的相关资料,文中分别介绍了利用itertools模块的groupby()方法和利用正则表达式是如何实现的,通过示例代码介绍的非常详细,需要的朋友们下面来一起看看吧。

前言

最近工作中遇到一个问题,需求是碰到'122333<<<<'这种字符串,要将其连贯的部分取出,得出['1', '22', '333', '<<<<']这样的列表,能想到的常规办法,遍历字符串,后一个与前一个逐个比较,这样真的很麻烦!又想到了另外两种方法,话不多说了,来一起看看详细的示例代码:

一、实际上可以借助itertools模块的groupby()方法来处理:


import itertools 
 
Str = &#39;122333<<<<&#39; 
Lst = [] 
for key,group in itertools.groupby(s): 
 Lst.append(list(group)) 
 
print map(lambda x: &#39;&#39;.join(x), Lst)
Copy after login

上面的处理,还是比较有技巧,也能得到想要的输出结果

['1', '22', '333', '<<<<']

二、但更酷点,更技巧处理方式是用正则表达式来处理:


import re 
 
Str = &#39;122333<<<<&#39; 
Lst = [] 
 
Pat = re.compile(r&#39;((.)\2*)&#39;) 
Rst = [x[0] for x in re.findall(Pat, Str)] 
 
print Rst
Copy after login

备注:

      1. (.)                # .匹配任意字符;(.)做分组,方便后面反向引用

      2. \2*                # \2对里面括号的反向引用;*代表是0个到多个;

      3. ((.)\2*)           # 连起来就是任意一个或多个字符组成的分组;

      4. (.)\1*             # 这种方式则可以取出唯一的值['1', '2', '3', '<'];同样非常方便

The above is the detailed content of Detailed explanation of using regular expressions to group strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template