Regex在试图提取“;当非x为零时”;
本文关键字:当非 零时 提取 Regex | 更新日期: 2023-09-27 18:27:55
我在C#中使用Regex匹配语句时遇到问题
Statement: "When Not x Is Nothing"
Pattern: "When Not ['.0-9a-zA-Z_()]* Is Nothing"
此模式还匹配语句"When x Is Nothing"
,我不希望发生这种情况。任何关于如何改进与预期语句匹配的建议都将不胜感激。
在LINQPad中,正则表达式似乎工作得很好(正如其他人所说)
来源:
var testStrings = new[]
{
"When Not x Is Nothing",
"When x Is Nothing",
};
var regex = new Regex("When Not [.0-9a-zA-Z_()]* Is Nothing");
foreach (var test in testStrings)
{
var match = regex.IsMatch(test);
String.Format("regex {0} matches string {1} ? {2}", regex, test, match).Dump();
}
结果:
regex When Not[.0-9a-zA-Z_()]*Is Nothing匹配字符串When Not x什么都没有?真实
regex When Not[.0-9a-zA-Z_()]*不匹配string当x为零时?错误
关于否决权的风险。这会将False
返回到控制台:
Regex rgx = new Regex(@"When Not [.0-9a-zA-Z_()]* Is Nothing");
Console.WriteLine(rgx.IsMatch("When x Is Nothing"));
所以我认为
- 您编写的正则表达式是错误的,或者至少与此处的正则表达式不一致
- 您在C#代码中做了一些错误的事情(例如,有一个指向错误正则表达式的指针)
- 您正在使用损坏的API
我个人会写:
Regex rgx = new Regex(@"^When Not [.0-9a-zA-Z_()]* Is Nothing$");
让它更安全,但我不知道你是在匹配字符串还是在搜索子字符串。