使用负向后看匹配字符串中的单词

时间:2018-08-03 13:31:42

标签: c# regex regex-negation regex-lookarounds

我尝试使用带有负向后看的模式来获得不以“ 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));

它总是返回完整的单词集,但应该仅返回轮次,排队

1 个答案:

答案 0 :(得分:2)

(?<!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
相关问题