user2277750
user2277750

Reputation: 11

Regex to find N (specified number) words before and after a specific word

Can someone help me doing following search using Regex in C#

I need a regex that will give me specific number of words before and after a specific word that will include the search word itself. Please note I want to be able to specify how many words before and after I want. If the search word is in the start of the text then it returns just the N number of words after the search word and vice-versa if the search word is in the end of the text. Also the search should be able to provide multiple matches from the text that I can process.

For instance I want to get "2" words around the search word "example" so that will return multiple results in following the multiline text.

"example one in this lesson is an example summary that we are using as an example. How many words are in this example? We only want the first few examples."

Returns following results

"example one in" (note how first search has no first 2 words)

"is an example summary that"

"as an example. How many"

"in this example? We only"

Thanks.

Upvotes: 1

Views: 1237

Answers (1)

MikeM
MikeM

Reputation: 27415

given your example the following regex would work

^example \w+ \w+|\w+ \w+ example[\.\?,]? \w+ \w+

Example C# implementation

string example = @"example one in this lesson is an example summary that we are using as an example. How many words are in this example? We only want the first few examples.";
string pattern = @"^example \w+ \w+|\w+ \w+ example[\.\?,]? \w+ \w+";

foreach (Match m in Regex.Matches(example, pattern))
{
    Response.Write(m.Value + "<br/>");
}

use a regex debugger (such as debuggex) or regex tester (such as regexpal) to do any fine tuning to the above as you try this on additional test cases.

Upvotes: 3

Related Questions