简体   繁体   中英

Python Regex - Split string after every character

I have a string that follows the pattern of a 1+ numbers followed by a single letter, 'a', 'b', 'c' . I want to split the string after every letter.

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

在此输入图像描述

I've tried so far

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

Your regex is backwards - it should be any number of digits followed by an a , b or a c . additionally, I wouldn't use split , which returns annoying empty strings, but findall :

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

If you're able to use the newer regex module , you can even split on zero-width matches (with lookarounds, that is).

import regex as re

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

This approach looks for one of az behind and a digit ( \\d ) immediately ahead.
The original re.split() does not allow zero-width matches, for compatibility you explicitely need to turn the new behaviour on with (?V1) in the pattern.
See a demo on regex101.com .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM