Python:重新查找两次的最快方法?

标签 python regex

我喜欢正则表达式。当尝试从大文本 block 中获取子字符串时,我经常发现自己使用多个正则表达式语句来缩小所需的值。

到目前为止,我的方法如下:

  1. 使用 resultOfRegex1 = re.findall(firstRegex, myString) 作为我的第一个正则表达式
  2. 检查 resultOfRegex1[0] 是否存在
  3. 使用 resultOfRegex2 = re.findall(secondRegex, resultOfRegex1[0]) 我的第二个正则表达式
  4. 检查 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/

相关文章:

python - 如何根据正则表达式检索 HTML 标签

python - 你能解释一下这个 Python 列表理解吗?

python - 如何用python获取网格和平面之间的横截面周长?

javascript - 如何编写正则表达式从 URL 获取参数

ruby - 正则表达式匹配文本周围的字符

C# 正则表达式总是返回 FALSE

regex - 通过两个字符标记将字符串拆分为列

python - 我正在计算观看次数,但这会导致错误

python - 如何比较列表中元组中的值

Python:在传递给另一个函数之前替换变量值