Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  • "dummy text to"
  • "with text and"

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

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*textS*(?:sS+)?

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 la@text.be to read";

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

the matches are:

dummy text to
with text and
Text is
my text.
a text-field example
dummy la@text.be to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...