Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Match words with shared spaces

Tags:

regex

spaces

How do I match specified words in a sentence? If I have the sentence "lord of the rings" and want to remove "of" and "the" how do I write the regex?

I don't want it to match anything in for example "don't match them" or "don't match often". It should match when "the" or "of" is in the beginning or end of the row as well.

The problem I encountered is when the words follow each other like in the example with "lord of the rings". When they share a space so to say.

The best I could manage is something like this:

/^(the|of) | (the|of)$| (of|the) /gmi

But it doesn't solve all my problems.

like image 919
Jimmy Garpehäll Avatar asked Dec 31 '25 08:12

Jimmy Garpehäll


2 Answers

This is a perfect task for word boundaries

\b(of|the)\b
like image 175
Gary Avatar answered Jan 03 '26 02:01

Gary


You can use the lookahead group (?= ) [doc]:

/^(the|of) | (the|of)$| (of|the)(?= )/gmi

Demo : https://regex101.com/r/Bo4Ur1/1

like image 23
Pandraghon Avatar answered Jan 03 '26 04:01

Pandraghon



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!