【问题标题】:Match words in string using negative lookbehind使用否定后向匹配字符串中的单词
【发布时间】:2019-01-11 10:00:59
【问题描述】:

我尝试使用带有否定后视的模式来获取不以 "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));

它总是返回完整的单词集,但应该只返回round, queue

【问题讨论】:

  • 如果单词分隔符总是 ; 你甚至不必使用正则表达式 - String.Split 结合 linq 就可以了
  • 注意有Regex类,而不是Regexp
  • Regex 别名为Regexp 有什么意义?还有RegexpOptions?

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


【解决方案1】:

(?&lt;!un)\w+\b 首先匹配一个前面没有un 的位置(带有否定的后视),然后匹配一个或多个单词字符后跟一个单词边界位置。

您需要在前导词边界之后使用否定前瞻

\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

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2023-03-11
    相关资源
    最近更新 更多