Python Regex - 在每个字符后分割字符串

时间:2016-05-23 20:18:18

标签: python regex python-3.x

我的字符串遵循1+数字后跟单个字母'a', 'b', 'c'的模式。我希望在每个字母后分割字符串。

some_function('12a44b65c')
>>> ['12a', '44b', '65c']

enter image description here

到目前为止我已经尝试了

re.split('([abc]\d+)', '12a44b65c')
>>> ['12', 'a44', '', 'b65', 'c']

2 个答案:

答案 0 :(得分:3)

您的正则表达式是向后的 - 它应该是任意数字后跟abc。另外,我不会使用split,它会返回恼人的空字符串,但是findall

>>> re.findall('(\d+[abc])', '12a44b65c')
['12a', '44b', '65c']

答案 1 :(得分:1)

如果你能够使用newer regex module,你甚至可以在零宽度匹配上进行分割(看起来就是这样)。

import regex as re

rx = r'(?V1)(?<=[a-z])(?=\d)'
string = "12a44b65c"
parts = re.split(rx, string)
print parts
# ['12a', '44b', '65c']

此方法会在后面查找a-z后面的一个和一个数字(\d) 原始re.split()不允许零宽度匹配,因为您明确需要在模式中使用(?V1)启用新行为的兼容性。
请参阅demo on regex101.com

相关问题