简体   繁体   English

找到Regex.Match失败的地方

[英]Find where Regex.Match failed

I want to know which Regex Groupcollection failed to match. 我想知道哪个Regex Groupcollection无法匹配。

eg: 例如:

My pattern detects VIEW start page or VIEW end via: 我的模式通过以下方式检测VIEW start pageVIEW end

match = Regex.Match(string, @"(^VIEW)\s*((?(1)(?:(start)\s*((?(1)page$))|(end$))))");

I want to know if I give the input string as "VIEW go" how to find that the second group failed. 我想知道我是否将输入字符串作为“VIEW go”如何找到第二组失败。

You don't have to check the latter group to verify if your regex matches something or not. 您不必检查后一组以验证您的正则表达式是否与某些内容匹配。

The Match Object returned by the method allow you to check this using: 方法返回的匹配对象允许您使用以下方法检查:

if ( match.Success )
    Console.Write("Success!");
else
    Console.Write("Expected start page or end after VIEW");

For you purpose you can also simplify your regex as this: 为了您的目的,您还可以简化您的正则表达式:

match = Regex.Match(string, @"^VIEW\s+(?:start\s+page|end)$");

See the online demo . 请参阅在线演示

UPDATE UPDATE

If you want to refine the error message you can try something like this: 如果要优化错误消息,可以尝试以下方法:

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]");
}

A running code demo on ideone 关于ideone的运行代码演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM