常用表达.在两个词之间匹配特定词 [英] Regular expressions. Match specific word between two words
问题描述
我使用C#.我有一个字符串:
I use C#. I have a string:
wordA wordB wordC wordB wordD
我需要匹配wordA和wordD之间所有出现的wordB.我使用lookahead和lookbehind来匹配wordA和worD之间的所有内容,如下所示:
I need to match all occurrences of wordB between wordA and wordD. I use lookahead and lookbehind to match everything between wordA and worD like this:
(?<=wordA)(.*?)(?=wordD)
但是类似
(?<=wordA)(wordB)(?=wordD)
不匹配任何内容.匹配单词A和单词D之间所有出现的单词B的最佳方法是什么?
matches nothing. What would be the best way to match all occurrences of wordB between wordA and wordD?
推荐答案
将.*?
放入环顾四周:
(?<=wordA.*?)wordB(?=.*?wordD)
请参见现在,该模式表示:
-
(?< = wordA.*?)
-(积极地向后看)要求存在wordA
,后跟任意0+个字符(尽可能少)紧接... -
wordB
-单词B -
(?=.*?wordD)
-(正向查找)要求存在任何0+个字符(尽可能少),后跟一个wordD
它们(因此,可以紧接在wordB
之后或某些字符之后).
(?<=wordA.*?)
- (a positive lookbehind) requires the presence ofwordA
followed with any 0+ chars (as few as possible) immediately before...wordB
- word B(?=.*?wordD)
- (a positive lookahead) requires the presence of any 0+ chars (as few as possible) followed with awordD
after them (so, it can be right afterwordB
or after some chars).
如果您需要考虑多行输入,请使用 RegexOptions.Singleline
标志编译正则表达式,以便.
可以与换行符匹配(或在模式前加上(?s)
内联修饰符选项-(?s)(?< = wordA.*?)wordB(?=.*?wordD)
).
If you need to account for multiline input, compile the regex with RegexOptions.Singleline
flag so that .
could match a newline symbol (or prepend the pattern with (?s)
inline modifier option - (?s)(?<=wordA.*?)wordB(?=.*?wordD)
).
如果单词"由字母/数字/下划线组成,并且您需要将它们作为整个单词进行匹配,请不要忘记将 wordA
, wordB
和带有 \ b
(单词边界)的 wordD
.
If the "words" consist of letters/digits/underscores, and you need to match them as whole words, do not forget to wrap the wordA
, wordB
and wordD
with \b
s (word boundaries).
始终在目标环境中测试您的正则表达式:
Always test your regexes in the target environment:
var s = "wordA wordB wordC wordB \n wordD";
var pattern = @"(?<=wordA.*?)wordB(?=.*?wordD)";
var result = Regex.Replace(s, pattern, "<<<$&>>>", RegexOptions.Singleline);
Console.WriteLine(result);
// => wordA <<<wordB>>> wordC <<<wordB>>>
// wordD
请参见 C#演示.
这篇关于常用表达.在两个词之间匹配特定词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!