我需要在按键行前后找到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+)?
答案 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)
答案 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;