正则表达式可在关键字前后找到2个单词

时间:2019-07-23 10:33:23

标签: c# regex

我需要在按键行前后找到2个单词,如下所示:

Here is a testing    string with    some more testing strings.

Keyword - with
Result  - "testing string with some more"

这是我准备的一个正则表达式,但不适用于两者之间的空格。

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

3 个答案:

答案 0 :(得分:4)

使用\S*时,这意味着要使用非空格字符,因此您的空格会成为障碍。
我建议使用以下正则表达式:(\S+)\s*(\S+)\s*with\s*(\S+)\s*(\S+),这意味着:

  • (\S+):不包含空格字符(一个单词)的文本。
  • /s*:零个或多个空格(在单词之间)

使用它后,您将得到4个组,分别与with之前的2个单词和其后面的2个单词相对应。

在这里尝试正则表达式:https://regex101.com/r/Mk67s2/1

答案 1 :(得分:3)

尝试一下:

([a-zA-Z]+\s+){2}with(\s+[a-zA-Z]+){2}

Here Is Demo

答案 2 :(得分:0)

尝试以下方法:

string testString = "Here is a testing    string with    some more testing strings.";
string keyword = "with";
string pattern = $@"\w+\s+\w+\s+{keyword}\s+\w+\s+\w+";
string match = Regex.Match(testString, pattern).Value;