Is there a pythonian or shorthand way to get all pattern occurrences from a string and their indices? I can write a method that does it, I'm just wondering if there's a super short one-liner or something :)
python re
module to the rescue.
>>> import re
>>> [x.start() for x in re.finditer('foo', 'foo foo foo foo')]
[0, 4, 8, 12]
re.finditer
returns a generator, what this means is that instead of using list-comprehensions you could use in in a for-loop
which would be more memory efficient.
You could extend this to get the span of your pattern in the given text. i.e. the start and end index.
>>> [x.span() for x in re.finditer('foo', 'foo foo foo foo')]
[(0, 3), (4, 7), (8, 11), (12, 15)]
Isn't Python Awesome :) couldn't stop myself from quoting XKCD, downvotes or no downvotes...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With