-2

Let's say I have the following string:

s = "once upon a time, there was once a person"

Without using findall to get all onces in the string:

>>> re.findall(r'\bonce\b', s)
['once', 'once']

Is there a way to use search incrementally, so it only returns the first occurrence and then increments the input string?

while (s):
    x = re.search(r'\bonce\b', s) # return 'once' and increment the string to s[4:]
    yield x
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

0

Use re.finditer()

for match in re.finditer(r'\bonce\b', s):
    yield match

Or you can just return the iterator rather than writing your own loop.

return re.finditer(r'\bonce\b', s)
Barmar
  • 741,623
  • 53
  • 500
  • 612