有没有办法在C#中获取捕获组的名称?
string line = "No.123456789 04/09/2009 999";
Regex regex = new Regex(@"(?<number>[\d]{9}) (?<date>[\d]{2}/[\d]{2}/[\d]{4}) (?<code>.*)");
GroupCollection groups = regex.Match(line).Groups;
foreach (Group group in groups)
{
Console.WriteLine("Group: {0}, Value: {1}", ???, group.Value);
}
Run Code Online (Sandbox Code Playgroud)
我想得到这个结果:
Group: [I don´t know what should go here], Value: 123456789 04/09/2009 999 Group: number, Value: 123456789 Group: date, Value: 04/09/2009 Group: code, Value: 999
Jef*_*tes 122
使用GetGroupNames获取表达式中的组列表,然后使用名称作为组集合中的键进行迭代.
例如,
GroupCollection groups = regex.Match(line).Groups;
foreach (string groupName in regex.GetGroupNames())
{
Console.WriteLine(
"Group: {0}, Value: {1}",
groupName,
groups[groupName].Value);
}
Run Code Online (Sandbox Code Playgroud)
whi*_*and 21
最简单的方法是使用此扩展方法:
public static class MyExtensionMethods
{
public static Dictionary<string, string> MatchNamedCaptures(this Regex regex, string input)
{
var namedCaptureDictionary = new Dictionary<string, string>();
GroupCollection groups = regex.Match(input).Groups;
string [] groupNames = regex.GetGroupNames();
foreach (string groupName in groupNames)
if (groups[groupName].Captures.Count > 0)
namedCaptureDictionary.Add(groupName,groups[groupName].Value);
return namedCaptureDictionary;
}
}
Run Code Online (Sandbox Code Playgroud)
一旦这个扩展方法到位,你可以得到如下名称和值:
var regex = new Regex(@"(?<year>[\d]+)\|(?<month>[\d]+)\|(?<day>[\d]+)");
var namedCaptures = regex.MatchNamedCaptures(wikiDate);
string s = "";
foreach (var item in namedCaptures)
{
s += item.Key + ": " + item.Value + "\r\n";
}
s += namedCaptures["year"];
s += namedCaptures["month"];
s += namedCaptures["day"];
Run Code Online (Sandbox Code Playgroud)
你应该使用GetGroupNames();
,代码看起来像这样:
string line = "No.123456789 04/09/2009 999";
Regex regex =
new Regex(@"(?<number>[\d]{9}) (?<date>[\d]{2}/[\d]{2}/[\d]{4}) (?<code>.*)");
GroupCollection groups = regex.Match(line).Groups;
var grpNames = regex.GetGroupNames();
foreach (var grpName in grpNames)
{
Console.WriteLine("Group: {0}, Value: {1}", grpName, groups[grpName].Value);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
55165 次 |
最近记录: |