编程语言
首页 > 编程语言> > python – 用于获取字符后字符串中所有数字的正则表达式

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

作者:互联网

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

C9: Title of object (foo, bar) [ch1, CH12,c03,4]

所以结果应该是:

1,12,03,4

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

 \[.*?(\d) = matches '1' only
 \[.*(\d) = matches '4' only
 \[*?(\d) = matches include '9' from the beginning

等等

任何帮助是极大的赞赏!

编辑:
我也需要在不使用str.split()的情况下执行此操作.

解决方法:

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

>>> 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']

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

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

这将找到所有数字,后面只有非[字符直到结尾.

标签:python,regex,python-3-x,regex-lookarounds,regex-greedy
来源: https://codeday.me/bug/20190609/1202083.html