简体   繁体   中英

Find where Regex.Match failed

I want to know which Regex Groupcollection failed to match.

eg:

My pattern detects VIEW start page or VIEW end via:

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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