【问题标题】:Python regular expression string search to return start indexPython正则表达式字符串搜索以返回开始索引
【发布时间】:2015-03-05 21:19:00
【问题描述】:

抱歉,如果这已经被问到了。 Python 3x 中有没有办法在字符串中搜索整个单词并返回其起始索引?

任何帮助将不胜感激。

【问题讨论】:

  • 任何整个单词或特定单词?
  • 查看match objects的文档。

标签: python string search


【解决方案1】:

是的,使用正则表达式和word boundary anchors:

>>> import re
>>> s = "rebar bar barbed"
>>> regex = re.compile(r"\bbar\b")
>>> for match in regex.finditer(s):
...     print(match.group(), match.start(), match.end())
...
bar 6 9

\b 锚确保只有整个单词可以匹配。如果您正在处理非 ASCII 单词,请使用 re.UNICODE 编译正则表达式,否则 \b 将无法按预期工作,至少在 Python 2 中不会。

【讨论】:

    【解决方案2】:

    如果您只想第一次出现,可以使用re.finditer 和下一个。

    s =  "foo  bar foobar"
    import re
    
    m = next(re.finditer(r"\bfoobar\b",s),"")
    if m:
       print(m.start())
    

    或者正如@Tim Pietzcker 评论的那样使用re.search

    import re
    m = re.search(r"\bfoobar\b",s)
    if m:
        print(m.start())
    

    【讨论】:

    • 如果您只想第一次出现,请使用re.search()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 2021-03-16
    • 1970-01-01
    • 2021-06-25
    • 2011-07-28
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多