正则表达式在特定单词之前和之后找到单词

我需要一个正则表达式,它在特定单词之前和之后给出了单词,包括搜索单词本身。

喜欢:“ 这是一些用于查找单词的虚拟文本 ”当文本是我的搜索词时,应该给我一串“虚拟文本 ”。

另一个问题是,提供的字符串可能包含多一次搜索字,因此我必须能够使用C#检索该字符串中的所有匹配项。

比如“ 这是一些虚拟文本,用于在字符串中查找带有文本和单词的单词 ”应返回:

  • “虚拟文字
  • “有文字和”

编辑:其实我应该返回包含搜索词的所有匹配项。 一些例子:文字太多了。 – >文字是

阅读我的文字。 – >我的文字

这是一个文本字段示例 – >一个文本字段示例

编辑:

如果你想在第一个单词之前从空格中获取所有内容到单词 use 之后的空格

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

一个简单的测试:

 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*text\S*(?:\s\S+)?", RegexOptions.IgnoreCase ); 

比赛是:

 虚拟文本
与文本和
文字是
我的文字。
文本字段示例
假la@text.be到 
 //I prefer this style for readability string pattern = @"(?\w+) text (?\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 */ 
 /[A-Za-z'-]+ text [A-Za-z'-]+/ 

应该适用于大多数情况,包括带连字符和复合词。

 ([Az]+) text ([Az]+) 

会很好的