A Developer
A Developer

Reputation: 1031

Regex to find 2 words before and after a keyword

I need to find 2 words before and after a keyrowrd like below:

Here is a testing    string with    some more testing strings.

Keyword - with
Result  - "testing string with some more"

Here is a regex I prepared but is not working for spaces in between.

(?:\S+\s)?\S*(?:\S+\s)?\S*text\S*(?:\s\S+)?\S*(?:\s\S+)?

Upvotes: 5

Views: 2696

Answers (3)

Michał Turczyn
Michał Turczyn

Reputation: 37367

Try below:

string testString = "Here is a testing    string with    some more testing strings.";
string keyword = "with";
string pattern = $@"\w+\s+\w+\s+{keyword}\s+\w+\s+\w+";
string match = Regex.Match(testString, pattern).Value;

Upvotes: 0

user11116003
user11116003

Reputation:

Try this:

([a-zA-Z]+\s+){2}with(\s+[a-zA-Z]+){2}

Here Is Demo

Upvotes: 3

Haytam
Haytam

Reputation: 4733

When you're using \S*, this means non-whitespace characters, so your spaces will get in the way.
I suggest the following regex: (\S+)\s*(\S+)\s*with\s*(\S+)\s*(\S+), whichs means:

  • (\S+): text that doesn't include whitespace characters (a word).
  • /s*: zero or more spaces (in between the words)

After using it, you'll get 4 groups that correspect to the 2 words before the with and 2 words after it.

Try the regex here: https://regex101.com/r/Mk67s2/1

Upvotes: 4

Related Questions