我喜欢正则表达式。当尝试从大文本 block 中获取子字符串时,我经常发现自己使用多个正则表达式语句来缩小所需的值。
到目前为止,我的方法如下:
- 使用
resultOfRegex1 = re.findall(firstRegex, myString)
作为我的第一个正则表达式 - 检查
resultOfRegex1[0]
是否存在 - 使用
resultOfRegex2 = re.findall(secondRegex, resultOfRegex1[0])
我的第二个正则表达式 - 检查
resultOfRegex2[0]
是否存在,并打印该值
但我觉得这比它应有的更加冗长和昂贵。是否有一种更简单/更快的方法来匹配一个正则表达式,然后根据第一个正则表达式的结果匹配另一个正则表达式?
最佳答案
组的全部意义在于允许从整体匹配中提取子组。
例如,两次搜索按照以下方式进行:
>>> import re
>>> s = 'The winning team scored 15 points and used only 2 timeouts'
>>> score_clause = re.search(r'scored \d+ point', s).group(0)
>>> re.search(r'\d+', score_clause).group(0)
'15'
对子组进行一次搜索:
>>> re.search(r'scored (\d+) point', s).group(1)
'15'
另一个想法:如果您想根据第一个匹配来决定是否继续 findall 式搜索,合理的选择是使用 re.finditer
并根据需要提取值:
>>> game_results = '''\
10 point victory: 1 in first period, 6 in second period, 3 in third period.
5 point victory: 0 in first period, 5 in second period, 0 in third period.
12 point victory: 5 in first period, 3 in second period, 4 in third period.
7 point victory: 3 in first period, 0 in second period, 4 in third period.
'''.splitlines()
>>> # Show period-by-period scores for games won by 8 or more points
>>> for game_result in game_results:
it = re.finditer(r'\d+', game_result)
if int(next(it).group(0)) >= 8:
print 'Big win:', [int(mo.group(0)) for mo in it]
Big win: [1, 6, 3]
Big win: [5, 3, 4]
关于Python:重新查找两次的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880387/