C# 使用反向查找匹配字符串中的单词

C# 使用反向查找匹配字符串中的单词,c#,regex,regex-negation,regex-lookarounds,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

我尝试使用带有负向后看的模式获取不以“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));
使用Regexp=System.Text.RegularExpressions.Regex;
使用RegexpOptions=System.Text.RegularExpressions.RegexOptions;
string quote=“地下;圆形;不稳定;唯一;队列”;
Regexp negativeViewBackward=new Regexp(@“(?The
)(?首先匹配前面没有
un
(带负查找)的位置,然后匹配一个或多个单词字符,后跟单词边界位置

您需要在前导词边界后使用负先行:

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

详细信息

  • \b
    -前导词边界
  • (?!un)
    -如果下两个单词字符是
    un
  • \w+
    -1+字字符
  • \b
    -尾随词边界
:


如果单词分隔符总是
你甚至不必使用正则表达式-
字符串。Split
与linq相结合就可以了。注意这里有
Regex
类,而不是
Regexp
Regex
作为
Regexp
regexptions
的点别名是什么?
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