【问题标题】:How can I get the offset where a Python regular expression search found a match?如何获取 Python 正则表达式搜索找到匹配项的偏移量?
【发布时间】:2013-04-06 22:58:43
【问题描述】:

我正在尝试使用 re.search() 获取匹配的偏移量。

http://docs.python.org/dev/howto/regex.html

该站点解释了如何获取匹配组件相对于匹配开始的偏移量,但没有说明如何在“haystack”字符串中获取匹配本身的偏移量。

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:
    >>> import re
    >>> s = 'Hello, this is a string'
    >>> m = re.search(',\s[a-z]',s)
    >>> m.group()
    ', t'
    >>> m.start()
    5
    

    更多信息可以在here找到。

    【讨论】:

    • 如果我使用已编译的正则表达式而不是 re.search,这是否会有所不同?
    • 没关系,我的愚蠢。我以为我误解了如何使用正则表达式,但事实证明我的正则表达式匹配的东西与我预期的不同。谢谢你的回答。
    • 好的,很高兴您解决了问题。
    【解决方案2】:

    你需要做这样的事情:

    import re
    
    for m in re.compile("[a-z]").finditer('what1is2'):
        print m.start(), m.group()
    

    【讨论】:

    • 我试过用match.start()但是默认是0组,也就是整场比赛,整场比赛相对于整场比赛的相对偏移量是0。
    • 没关系,我的愚蠢。我以为我误解了如何使用正则表达式,但事实证明我的正则表达式匹配的东西与我预期的不同。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2021-08-15
    相关资源
    最近更新 更多