regex to extract 5 words after the match

Viewed 186

I'm trying to create a regex in my app and having trouble understanding it. I've created one regex but still, I want it to be modified to do not match specific things. I need to create regex for both iOS and Android.

This is my regex

(?:rahul[\s"'?.!:s()\{\}])

This is my test string

rahul hello rahul! vyas and rahul? and rahul. and rahul: and rahul and rahul( and rahul) and rahul{ rahul.shiv  rahuls vyas rips rahul!!

This is the site I'm using to create the regex Regex Creator

What I actually want to match is if user type word rahul then it should match all rahul words including punctuations or if the word has s in it in the end. It should not select rahul.shiv.

Also is it possible to extract 5 words after the match and before the match. lets assume the word is in the middle of the sentence and I need to extract 5 words as prefix of the match and 5 words as suffix of the match. If anyone knows how to create this regex kindly answer the question with explanation.

Update - Screenshot for above matches enter image description here

Update 2 for Second regex demo enter image description here

The third capture group is only matching 2 words instead of 5 words.

1 Answers

For finding all the matches for your search word use:

\brahuls?[^\s\w]*(?=\s|$)

RegEx Demo

RegEx Details:

  • \b; Word boundary
  • rahuls?: Search word followed by an optional s
  • [^\s\w]*: Match 0 or more non-whitespace non-word characters
  • (?=\s|$): Must be followed by a whitespace or end of line

For allowing up to 5 words before and after the match use this regex with 3 capture groups:

(\b(?:\S+\s+){0,5}?)(\brahuls?[^\s\w]*(?=\s|$))(?=((?:\s+\S+){0,5}))

RegEx Demo 2

  • (\b(?:\S+\s+){0,5}?): Capture group #1 to lazily match 0 to 5 words before search word
  • (\brahuls?[^\s\w]*(?=\s|$)): Capture group #2 to match search word as per regex above
  • (?=((?:\s+\S+){0,5})): Capture group #3 to match 0 ot 5 words after the search word. Please note that this group is inside a lookahead to allow us to match overlapping matches
Related