regex to find a word before and after a specific word

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

Leave a Comment