PitAttack76
PitAttack76

Reputation: 2220

regex to find a word before and after a specific word

I need a regex that gives me the word before and after a specific word, included the search word itself.

Like: "This is some dummy text to find a word" should give me a string of "dummy text to" when text is my search word.

Another question, it's possible that the string provided will contain more then once the search word so I must be able to retrieve all matches in that string with C#.

Like "This is some dummy text to find a word in a string full with text and words" Should return:

EDIT: Actually I should have all the matches returned that contain the search word. A few examples: Text is too read. -> Text is

Read my text. -> my text

This is a text-field example -> a text-field example

Upvotes: 13

Views: 51156

Answers (5)

Khalid Enany
Khalid Enany

Reputation: 33

[a-zA-Z]+\stext\s[a-zA-Z]+

I believe this will work nicely

Upvotes: 0

Oleks
Oleks

Reputation: 32323

EDIT:

If you want to grab all the content from the space before first word to the space after the word use:

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

A simple tests:

string input = @"
    This is some dummy text to find a word in a string full with text and words
    Text is too read
    Read my text.
    This is a text-field example
    this is some dummy [email protected] to read";

var matches = Regex.Matches(
    input,
    @"(?:\S+\s)?\S*text\S*(?:\s\S+)?",
    RegexOptions.IgnoreCase
);

the matches are:

dummy text to
with text and
Text is
my text.
a text-field example
dummy [email protected] to

Upvotes: 17

Trey Carroll
Trey Carroll

Reputation: 2382

//I prefer this style for readability

string pattern = @"(?<before>\w+) text (?<after>\w+)";
string input = "larry text bob fred text ginger fred text barney";
MatchCollection matches = Regex.Matches(input, pattern);

for (int i = 0; i < matches.Count; i++)
{
    Console.WriteLine("before:" + matches[i].Groups["before"].ToString());
    Console.WriteLine("after:" + matches[i].Groups["after"].ToString());
} 

/* Output:
before:larry
after:bob
before:fred
after:ginger
before:fred
after:barney
*/

Upvotes: 7

eykanal
eykanal

Reputation: 27017

/[A-Za-z'-]+ text [A-Za-z'-]+/

Should work in most cases, including hyphenated and compound words.

Upvotes: 2

netbrain
netbrain

Reputation: 9304

([A-z]+) text ([A-z]+)

would do nicely

Upvotes: 1

Related Questions