Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a phrase that is NOT at a word boundary from a string in Regex?

Tags:

python

regex

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

like image 227
LearningCoding Avatar asked Jan 23 '26 10:01

LearningCoding


1 Answers

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.

Explanation

\b = a word boundary
(?!ro) = not followed by ro
\w+ = one or more word characters
(?<!ro)\b = another word boundary, not preceded by ro

Working Example

https://regex101.com/r/WcSlsx/2/

like image 161
hoipolloi Avatar answered Jan 25 '26 23:01

hoipolloi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!