用于获取字符后字符串中所有数字的正则表达式

Kei*_*rke 4 python regex python-3.x regex-greedy regex-lookarounds

我试图解析以下字符串并返回最后一个方括号后的所有数字:

C9: Title of object (foo, bar) [ch1, CH12,c03,4]
Run Code Online (Sandbox Code Playgroud)

所以结果应该是:

1,12,03,4
Run Code Online (Sandbox Code Playgroud)

字符串和数字会改变.重要的是得到'['之后的数字,不管它前面有什么字符(如果有的话).(我在python中需要这个,所以也没有原子组!)我已经尝试了我能想到的一切,包括:

 \[.*?(\d) = matches '1' only
 \[.*(\d) = matches '4' only
 \[*?(\d) = matches include '9' from the beginning
Run Code Online (Sandbox Code Playgroud)

等等

任何帮助是极大的赞赏!

编辑:我也需要这样做而不使用str.split().

Roh*_*ain 5

您可以在最后一个[括号后找到子字符串中的所有数字:

>>> s = 'C9: Title of object (fo[ 123o, bar) [ch1, CH12,c03,4]'
>>> # Get substring after the last '['.
>>> target_string = s.rsplit('[', 1)[1]
>>>
>>> re.findall(r'\d+', target_string)
['1', '12', '03', '4']
Run Code Online (Sandbox Code Playgroud)

如果你不能使用split,那么这个可以使用前瞻断言:

>>> s = 'C9: Title of object (fo[ 123o, bar) [ch1, CH12,c03,4]'
>>> re.findall(r'\d+(?=[^[]+$)', s)
['1', '12', '03', '4']
Run Code Online (Sandbox Code Playgroud)

这将查找所有数字,[直到结尾仅跟随非字符.