Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式在关键字前后查找2个单词_C#_Regex - Fatal编程技术网

C# 正则表达式在关键字前后查找2个单词

C# 正则表达式在关键字前后查找2个单词,c#,regex,C#,Regex,我需要在键盘前后找到两个单词,如下所示: 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+)? 当您使用\S*时,这意味着非空白字符,因此空格会

我需要在键盘前后找到两个单词,如下所示:

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+)?

当您使用
\S*
时,这意味着非空白字符,因此空格会妨碍您。
我建议使用以下正则表达式:
(\S+)\S*(\S+)\S*和\S*(\S+)\S*(\S+)
,这意味着:

  • (\S+)
    :不包含空白字符(单词)的文本
  • /s*
    :零个或多个空格(在单词之间)
使用后,您将得到4组与
前面的2个单词相对应的单词,其中包含
和后面的2个单词

在此处尝试正则表达式:

尝试以下操作:

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

尝试以下操作:

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;