我有一个包含字母数字值的字符串。数值是变量。字母值始终是 'abc'
和 'ghi'
,但我不知道它们的顺序。
数值总是在字母值之后。
这种字符串的有效例子是:
a = 'abc10ghi1450'
b = 'abc11ghi9285'
c = 'ghi1abc9'
...
现在我想将 'abc'
和 'ghi'
之后的数字存储到适当的变量中,我正在做的是:
>>> import re
>>> string = 'abc10ghi44'
>>> abc = re.search('abc\d+', string).group(0)
>>> abc = re.search('\d+', abc).group(0)
>>> ghi = re.search('ghi\d+', string).group(0)
>>> ghi = re.search('\d+', ghi).group(0)
>>> print abc, ghi
10, 44
对于每个变量,我使用了 2 个正则表达式,但我不喜欢它;有没有更聪明的方法来做同样的事情?
最佳答案
是的,围绕数字创建一个捕获组并使用它:
>>> import re
>>> string = 'abc10ghi44'
>>> re.search('abc(\d+)', string).group(1)
'10'
请注意 group
调用中 \d+
和 1
两边的括号。
或者,使用正面回顾:
>>> re.search('(?<=abc)\d+', string).group(0)
'10'
关于python - 嵌套正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30080731/