A Developer
A Developer

Reputation: 1031

Regex to find 5 words before and after a word

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

You can use

(?:\S+ +){0,5}\bHELLO(?:[:%-]\w+)*\b(?: +\S+){0,5}

Note:

  • The - 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.
  • Escape ^ if you put it at the start of the character class
  • Escape ] if you do not put it at the start of the character class.
  • Always escape \ 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

Related Questions