我正在尝试分析以下字符串并返回最后一个方括号后的所有数字:
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']
如果不能使用拆分,那么这将与前瞻性断言一起工作:
>>> s = 'C9: Title of object (fo[ 123o, bar) [ch1, CH12,c03,4]'
>>> re.findall(r'\d+(?=[^[]+$)', s)
['1', '12', '03', '4']
这将查找所有数字,这些数字后面只有非-
[
字符,直到结束。