0

After using .finditer() on a string I want to extract the index of the 'Match object; span=(xx,xx) and use them in a print(search_text[xx:xx]) statement.

How would I extract the locations of the search results.

matches = search_pattern.finditer(search_text) print(search_text[xx:xx]) # need to find a way to get the slice indexes

bigollo
  • 1
  • 1
  • 6

2 Answers2

0

You can use the span method

matches = search_pattern.finditer(search_text)
print ([m.span() for m in matches])
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

I think your question might have already been answered. Look here: Python Regex - How to Get Positions and Values of Matches

Peter Hoffmann gave this answer (which I linked above):

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

Please let me know if this does not help.

Cindy LB
  • 11
  • 3
  • If you think a question is a duplicate, vote to close as a duplicate, or flag as a duplicate if you don't have voting permissions yet; don't write an answer. – abarnert Jun 18 '18 at 23:33
  • I'm somewhat new so thank you for letting me know. Did you go ahead and flag it (or close it as duplicate)? Looks like someone went ahead and did so. Good to know. Thanks again. – Cindy LB Jun 18 '18 at 23:35
  • Nevermind, @abarnert - I see you did close it as a duplicate and provided them the link. Thanks again. I'm learning! – Cindy LB Jun 18 '18 at 23:37
  • No problem. Closing as a dup automatically adds the link to the duplicate question. Flagging… I think it adds the link as a comment, but I'm not sure. Anyway, you should have enough rep to start voting directly soon. – abarnert Jun 18 '18 at 23:41