Python正则表达式字符串搜索返回起始索引

时间:2015-03-05 21:19:01

标签: python string search

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

是的,使用正则表达式和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中工作。

答案 1 :(得分:1)

如果您只是想要第一次出现,可以使用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())