2015-04-22 58 views
2

我知道如何使用Python字符串中的报告精确匹配:如何找到完全匹配的索引?

import re 
word='hello,_hello,"hello' 
re.findall('\\bhello\\b',word) 
['hello', 'hello'] 

如何报告的精确匹配的指数? (在这种情况下,0和14)

+0

退房此链接。类似的问题http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python –

+0

可能的重复[查找Python的所有正则表达式匹配的索引?](http:// stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches-in-python) – HamZa

回答

0

使用finditer

[(g.start(), g.group()) for g in re.finditer('\\b(hello)\\b',word)] 
# [(0, 'hello'), (14, 'hello')] 
+0

This works。谢谢! – Sirian

+0

@ Sirian随时可以[接受并投票](http://stackoverflow.com/help/someone-answers)。干杯! – tzaman

1

改用word.find( '你好',X)

word = 'hello,_hello,"hello' 
tmp = 0 
index = [] 
for i in range(len(word)): 
    tmp = word.find('hello', tmp) 
    if tmp >= 0: 
     index.append(tmp) 
     tmp += 1 
+0

'str.find'将返回所有出现的内容,而不考虑问题中所需的字边界条件。 – tzaman