3

I know how to use python to report exact match in a string:

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

How do I report the indices of the exact matches? (in this case, 0 and 14)

tzaman
  • 46,925
  • 11
  • 90
  • 115
Sirian
  • 31
  • 1
  • Check out this link. Similar question http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python – Saicharan S M Apr 22 '15 at 21:12
  • possible duplicate of [Find the indexes of all regex matches in Python?](http://stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches-in-python) – HamZa Apr 22 '15 at 22:02

2 Answers2

1

Use finditer:

[(g.start(), g.group()) for g in re.finditer('\\b(hello)\\b',word)]
# [(0, 'hello'), (14, 'hello')]
tzaman
  • 46,925
  • 11
  • 90
  • 115
1

instead use word.find('hello',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
Max
  • 199
  • 1
  • 5
  • `str.find` will return all occurrences, without respecting the word boundary condition as desired in the question. – tzaman Apr 22 '15 at 21:20