Reputation: 1031
I need to write a Regex to find 5 words before and after a word. Here is what I have -
(?:\S+ +){0,5}\bHELLO\b(?: \S+){0,5}
It matches fine for :
WORD WORD WORD WORD WORD WORD HELLO WORD WORD WORD WORD WORD WORD WORD WORD
But not in : WORD WORD WORD WORD WORD WORD HELLO-1 WORD WORD WORD WORD WORD WORD WORD WORD
How can I include - or any specific special char in regex.
Upvotes: 2
Views: 47
Reputation: 627292
You can use
(?:\S+ +){0,5}\bHELLO(?:[:%-]\w+)*\b(?: +\S+){0,5}
Note:
-
char is at the end of the character class, where it does not have to escaped. If you put it at the start of the character class, you won't have to escape it either. Else, escape it.^
if you put it at the start of the character class]
if you do not put it at the start of the character class.\
char.The (?:[:%-]\w+)*
pattern is a non-capturing group that matches zero or more repetitions (due to *
) of a :
, %
or -
char followed with one or more word chars.
Upvotes: 1