简体   繁体   中英

C# Simple regex name group capturing

I have this simple code to capture named regex groups in C#, but only one of the name group value is non-empty. Any help would be really appreciated.

var formatter = "yyyy-MM-dd";

var regex = new Regex("(?<month>MM)|(?<day>dd)|(?<year>yyyy|yy)|([^a-zA-Z])");

var match = regex.Match(formatter);

if (match.Success)
{
    var day = match.Groups["day"];
    var month = match.Groups["month"];
    var year = match.Groups["year"];
}

Only one will get a value because of the OR operator |. Use the following

(?<year>yyyy)-(?<month>MM)-(?<day>dd)

I'm not too sure why you match on ([^a-zA-Z]) at the end, but you might want to try this: ((?<month>MM)|(?<day>dd)|(?<year>yyyy|yy)|(-))*

If it doesn't work for you, let me know why you match the end part.

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