【问题标题】:When using "re.search", how do I search for the second instance rather than the first?使用“re.search”时,如何搜索第二个实例而不是第一个?
【发布时间】:2019-07-17 21:21:42
【问题描述】:

re.search 查找某事物的第一个实例。在下面的代码中,“\t”出现了两次。有没有办法让它跳到第二个实例?

code = ['69.22\t82.62\t134.549\n']
list = []
text = code
m = re.search('\t(.+?)\n', text)
if m:
    found = m.group(1)
    list.append(found)

结果:

list = ['82.62\t134.549']

预期:

list = ['134.549']

【问题讨论】:

  • 如果有 4 个选项卡,需要哪个匹配项?
  • 或者将模式放入两次,其中一组不包括模式([^\t]+);或者在两者之间使用非贪婪匹配,就像您现在所做的那样。
  • @00 非贪婪无济于事。这会缩短右侧的匹配,而不是左侧的匹配。
  • 对于大于“第二”选项卡只有一种解决方案。那是^(?:[^\t]*\t){2}(.*?)\n
  • @sln 将其作为答案发布

标签: python regex


【解决方案1】:

您的表达式的这个修改版本确实返回了所需的输出:

import re

code = '69.22\t82.62\t134.549\n'
print(re.findall(r'.*\t(.+?)\n', code))

输出

['134.549']

我猜你可能想设计一个表达式,有点类似于:

(?<=[\t])(.+?)(?=[\n])

DEMO

【讨论】:

    【解决方案2】:

    对于大于“第二个”选项卡只有一种解决方案。
    你可以这样做:

    ^(?:[^\t]*\t){2}(.*?)\n

    解释

     ^                     # BOS
     (?:                   # Cluster
          [^\t]*                # Many not tab characters
          \t                    # A tab
     ){2}                  # End cluster, do 2 times
     ( .*? )               # (1), anything up to
     \n                    # first newline
    

    Python 代码

    >>> import re
    >>> text = '69.22\t82.62\t134.549\n'
    >>> m = re.search('^(?:[^\t]*\t){2}(.*?)\n', text)
    >>> if m:
    >>>     print( m.group(1) )
    ...
    134.549
    >>>
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2021-12-16
      • 2020-02-14
      • 2022-01-05
      • 2017-02-26
      • 2011-07-13
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多