【问题标题】:Python re find start and end index of group matchPython重新查找组匹配的开始和结束索引
【发布时间】:2021-04-11 16:02:53
【问题描述】:

Python 的重新匹配对象在匹配对象上有 .start() 和 .end() 方法。 我想找到小组赛的开始和结束索引。我怎样才能做到这一点? 示例:

>>> import re
>>> REGEX = re.compile(r'h(?P<num>[0-9]{3})p')
>>> test = "hello h889p something"
>>> match = REGEX.search(test)
>>> match.group('num')
'889'
>>> match.start()
6
>>> match.end()
11
>>> match.group('num').start()                  # just trying this. Didn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'start'
>>> REGEX.groupindex
mappingproxy({'num': 1})                        # this is the index of the group in the regex, not the index of the group match, so not what I'm looking for.

上面的预期输出是 (7, 10)

【问题讨论】:

    标签: python python-re


    【解决方案1】:

    给定示例的解决方法可能是使用lookarounds:

    import re
    REGEX = re.compile(r'(?<=h)[0-9]{3}(?=p)')
    test = "hello h889p something"
    match = REGEX.search(test)
    print(match)
    

    输出

    <re.Match object; span=(7, 10), match='889'>
    

    【讨论】:

      【解决方案2】:

      您可以只使用字符串索引和index() 方法:

      >>> import re
      >>> REGEX = re.compile(r'h(?P<num>[0-9]{3})p')
      >>> test = "hello h889p something"
      >>> match = REGEX.search(test)
      >>> test.index(match.group('num')[0])
      7
      >>> test.index(match.group('num')[-1])
      9
      

      如果你想要一个元组的结果:

      >>> str_match = match.group("num")
      >>> results = (test.index(str_match[0]), test.index(str_match[-1]))
      >>> results
      (7, 9)
      

      注意:作为Tom pointed out,您可能需要考虑使用results = (test.index(str_match), text.index(str_match)+len(str_match)),以防止可能由具有相同字符的字符串引起的错误。例如,如果数字是899,那么results 将是(7, 8),因为9 的第一个实例位于索引8。

      【讨论】:

        【解决方案3】:

        the existing answer稍作修改是使用index查找整个组,而不是组的起止字符:

        import re
        REGEX = re.compile(r'h(?P<num>[0-9]{3})p')
        test = "hello h889p something"
        match = REGEX.search(test)
        group = match.group('num')
        
        # modification here to find the start point
        idx = test.index(group)
        
        # find the end point using len of group
        output = (idx, idx + len(group)) #(7, 10)
        

        这会在确定索引时检查整个字符串 "889"。因此,与检查第一个8 和第一个9 相比,出错的可能性要小一些,尽管它仍然不完美(即,如果"889" 出现在字符串的前面,而不是被"h" 和@ 包围987654329@).

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-15
          • 2022-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-02
          • 2017-10-08
          • 2022-01-10
          相关资源
          最近更新 更多