Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将包含重复字符的字符串拆分为列表_Python_Regex_String - Fatal编程技术网

Python 将包含重复字符的字符串拆分为列表

Python 将包含重复字符的字符串拆分为列表,python,regex,string,Python,Regex,String,我对正则表达式没有很好的经验,但我已经读了很多关于它的书。假设有一个字符串s='111234'我想要一个列表,其中字符串拆分为L=['111','2','3','4']。我的方法是让一个小组检查它是否是一个数字,然后检查小组的重复。像这样的 L = re.findall('\d[\1+]', s) 我认为\d[\1+]基本上会检查相同重复的“数字”或“数字+”。我想这可能是我想要的 试试这个: s = '111234' l = re.findall(r'((.)\2*)', s) ## it

我对正则表达式没有很好的经验,但我已经读了很多关于它的书。假设有一个字符串
s='111234'
我想要一个列表,其中字符串拆分为
L=['111','2','3','4']
。我的方法是让一个小组检查它是否是一个数字,然后检查小组的重复。像这样的

L = re.findall('\d[\1+]', s)
我认为
\d[\1+]
基本上会检查相同重复的“数字”或“数字+”。我想这可能是我想要的

试试这个:

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
输出:

['111', '2', '3', '4']

如果要对所有重复的字符进行分组,那么也可以使用,如下所示

from itertools import groupby
print ["".join(grp) for num, grp in groupby('111234')]
# ['111', '2', '3', '4']
如果要确保只需要数字,则

print ["".join(grp) for num, grp in groupby('111aaa234') if num.isdigit()]
# ['111', '2', '3', '4']
使用:


你知道字符串是否只包含数字吗?@thefourtheye:不,假设它也包含非数字。我觉得你在找
r_e=“(1*)(2*)(3*)(4*)”
,它给出了
re.findall(r_e,s)[0]
('111',2',3',4')
。通过列表是有序的集合:如果您不需要顺序,那么您可以使用
r_e=“(((?P1+))(?P2+)(?P3+)(?P4+))”
然后
重新搜索(r_e,s).组('o','to','th','f')
为什么创建元组?是因为有两组被发现吗?是的,这两组都有。
>>> s='111234'
>>> [m.group(0) for m in re.finditer(r"(\d)\1*", s)]
['111', '2', '3', '4']