Okay so this may be just googling wrong or not reading documentation correctly, but I couldn't find anything on this.
Say I have:
sample_str = "rose aaron robert moro"
pat = 'ro'
I want to find all instances of words (preferably using re.search()) which DON'T end OR begin in 'ro'. That is, I want one or more character to be before and after 'ro'. So I would want 'aaron' to match, but not at any of the other words in sample_str.
How would I do this? I tried a bunch of things, including '+ro+', but it gave me an error. I am not new to Python but have some trouble with the Regex, so if anyone can please explain that would be great.
Thanks
I believe you can use a negative look-ahead/look-behind for this.
\b(?!ro)\w+(?<!ro)\b
When applied to rose aaron robert moro will match only aaron.
\b = a word boundary
(?!ro) = not followed by ro
\w+ = one or more word characters
(?<!ro)\b = another word boundary, not preceded by ro
https://regex101.com/r/WcSlsx/2/
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