[英]Find where Regex.Match failed
我想知道哪个Regex Groupcollection无法匹配。
例如:
我的模式通过以下方式检测VIEW start page
或VIEW end
:
match = Regex.Match(string, @"(^VIEW)\s*((?(1)(?:(start)\s*((?(1)page$))|(end$))))");
我想知道我是否将输入字符串作为“VIEW go”如何找到第二组失败。
您不必检查后一组以验证您的正则表达式是否与某些内容匹配。
方法返回的匹配对象允许您使用以下方法检查:
if ( match.Success )
Console.Write("Success!");
else
Console.Write("Expected start page or end after VIEW");
为了您的目的,您还可以简化您的正则表达式:
match = Regex.Match(string, @"^VIEW\s+(?:start\s+page|end)$");
请参阅在线演示 。
UPDATE
如果要优化错误消息,可以尝试以下方法:
match = Regex.Match(string, @"^VIEW\s+(?:(start\s+page|end)|(.*))$");
if (match.Success) {
if ( match.Groups[1].Success)
Console.Write("Success!");
if ( match.Groups[2].Success)
Console.Write("Expected start page or end after VIEW");
} else {
Console.Write("usage: VIEW [start page|end]");
}
关于ideone的运行代码演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.