C#正则表达式根据分组命名取值
时间: 2023-06-28 21:05:24 浏览: 49
在 C# 中,可以通过使用分组命名的方式来对正则表达式的匹配结果进行标识,并且可以方便地获取每个分组的值。
下面是一个示例正则表达式:
```
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})
```
这个正则表达式可以匹配形如“2019-01-01”这样的日期字符串,并将年、月、日分别保存到名为“year”、“month”、“day”的分组中。
接下来是一个示例代码,用于演示如何根据分组命名取得正则表达式匹配的值:
```csharp
string pattern = @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})";
string input = "2019-01-01";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
string year = match.Groups["year"].Value;
string month = match.Groups["month"].Value;
string day = match.Groups["day"].Value;
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", year, month, day);
}
```
在这段代码中,我们先定义了一个正则表达式,接着使用 Regex.Match 方法对输入字符串进行匹配,然后通过 match.Groups["分组名"].Value 的方式获取每个分组的值,并输出到控制台上。