使用正则表达式将带有重复字符的字符串拆分到列表中

Mat*_*M_J 18 python regex string

我对Regex没有很好的经验,但我一直在阅读很多相关内容.假设有一个字符串s = '111234'我想要一个字符串拆分成的列表L = ['111', '2', '3', '4'].我的方法是让一个小组检查它是否是一个数字,然后检查该组的重复.像这样的东西

L = re.findall('\d[\1+]', s)
Run Code Online (Sandbox Code Playgroud)

我认为这\d[\1+]基本上会检查"数字"或"数字+"相同的重复.我想这可能会做我想要的.有人可以帮忙吗?

dev*_*ull 16

用途re.finditer():

>>> s='111234'
>>> [m.group(0) for m in re.finditer(r"(\d)\1*", s)]
['111', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)


the*_*eye 15

如果要对所有重复的字符进行分组,那么您也可以itertools.groupby像这样使用

from itertools import groupby
print ["".join(grp) for num, grp in groupby('111234')]
# ['111', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)

如果你想确保只想要数字,那么

print ["".join(grp) for num, grp in groupby('111aaa234') if num.isdigit()]
# ['111', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)


Sab*_*san 7

试试这个:

s = '111234'

l = re.findall(r'((.)\2*)', s)
## it this stage i have [('111', '1'), ('2', '2'), ('3', '3'), ('4', '4')] in l

## now I am keeping only the first value from the tuple of each list
lst = [x[0] for x in l]

print lst
Run Code Online (Sandbox Code Playgroud)

输出:

['111', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)