Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套正则表达式_Python_Regex - Fatal编程技术网

Python 嵌套正则表达式

Python 嵌套正则表达式,python,regex,Python,Regex,我有一个带有字母数字值的字符串。数值是变量。字母值总是'abc'和'ghi',但我不知道它们的顺序。 数字值始终位于字母值之后 此类字符串的有效示例有: a = 'abc10ghi1450' b = 'abc11ghi9285' c = 'ghi1abc9' ... 现在我想将'abc'和'ghi'之后的数字存储到适当的变量中,我要做的是: >>> import re >>> string = 'abc10ghi44' >>> abc =

我有一个带有字母数字值的字符串。数值是变量。字母值总是
'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'
注意
组调用中
\d+
1
周围的括号


或者,使用积极的回顾:

>>重新搜索('(?)?
>>> re.search('(?<=abc)\d+', string).group(0)
'10'