Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match max 5 words before and after a certain word

Tags:

regex

I need a regex that will match at most 5 words before and after a certain word. Example:

the certain word is "the"

the string is "John Ely gets start for the Dodgers, while old friend Takashi Saito gets start for the Brewers in what will essentially be a bullpen game for Milwaukee."

There should be 2 results:

John Ely gets start for the Dodgers, while old friend Takashi

Takashi Saito gets start for the Brewers in what will essentially

Any ideas???

Thanks

like image 462
Rick Avatar asked Feb 25 '23 21:02

Rick


2 Answers

(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}the(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5}

Note however that most regex engines won't deal with overlapping matches.

like image 115
Amber Avatar answered Mar 04 '23 04:03

Amber


Here is what seems to work regarding the question asked. (?:\s*\w+\s+){0,5}the(?:\s*\w+\s*){0,5}

like image 29
pmntang Avatar answered Mar 04 '23 04:03

pmntang