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*
前面的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;