简体   繁体   English

C#简单正则表达式名称组捕获

[英]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. 我有这个简单的代码来捕获C#中的命名正则表达式组,但是只有一个名称组值是非空的。 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 |. 由于OR运算符|,只有一个将获得值。 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)|(-))* 我不太确定为什么最后要在([^a-zA-Z])上进行匹配,但是您可能想尝试一下: ((?<month>MM)|(?<day>dd)|(?<year>yyyy|yy)|(-))*

If it doesn't work for you, let me know why you match the end part. 如果对您不起作用,请告诉我为什么您要匹配末端部分。

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

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