将具有重复字符的字符串拆分为列表 [英] Splitting a string with repeated characters into a list

查看:64
本文介绍了将具有重复字符的字符串拆分为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Regex 的经验并不丰富,但我已经阅读了很多关于它的内容.假设有一个字符串 s = '111234' 我想要一个列表,该列表将字符串拆分为 L = ['111', '2', '3', '4'].我的方法是让一组检查它是否是数字,然后检查该组是否重复.类似这样的

L = re.findall('\d[\1+]', s)

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

解决方案

使用 re.finditer():

<预><代码>>>>s='111234'>>>[m.group(0) for m in re.finditer(r"(\d)\1*", s)]['111', '2', '3', '4']

I am not well experienced with Regex but I have been reading a lot about it. Assume there's a string s = '111234' I want a list with the string split into L = ['111', '2', '3', '4']. My approach was to make a group checking if it's a digit or not and then check for a repetition of the group. Something like this

L = re.findall('\d[\1+]', s)

I think that \d[\1+] will basically check for either "digit" or "digit +" the same repetitions. I think this might do what I want.

解决方案

Use re.finditer():

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

这篇关于将具有重复字符的字符串拆分为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆