Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

c# - 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:

  • "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

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

1 Reply

0 votes
by (71.8m points)

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 [email protected] 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 [email protected] to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...