使用否定后视匹配字符串中的单词

Match words in string using negative lookbehind

我尝试使用负后视模式获取不以 "un" 开头的单词。这是代码:

using Regexp = System.Text.RegularExpressions.Regex;
using RegexpOptions = System.Text.RegularExpressions.RegexOptions;

string quote = "Underground; round; unstable; unique; queue";
Regexp negativeViewBackward = new Regexp(@"(?<!un)\w+\b", RegexpOptions.IgnoreCase);
MatchCollection finds = negativeViewBackward.Matches(quote);

Console.WriteLine(String.Join(", ", finds));

总是return的全套的话,但是应该return只轮,队列

(?<!un)\w+\b首先匹配一个不以un开头的位置(负向后看),然后匹配1个或多个单词字符后跟单词边界位置。

您需要在前导词边界后使用负前瞻

\b(?!un)\w+\b

参见regex demo

详情

  • \b - 前导词边界
  • (?!un) - 如果接下来的两个单词字符是 un
  • ,则匹配失败的否定前瞻
  • \w+ - 1+ 个单词字符
  • \b - 尾随单词边界。

C# demo:

string quote = "Underground; round; unstable; unique; queue";
Regex negativeViewBackward = new Regex(@"\b(?!un)\w+\b", RegexOptions.IgnoreCase);
List<string> result = negativeViewBackward.Matches(quote).Cast<Match>().Select(x => x.Value).ToList();
foreach (string s in result)
    Console.WriteLine(s);

输出:

round
queue