Làm cách nào để lấy tên của các nhóm đã bắt trong C # Regex?


97

Có cách nào để lấy tên của một nhóm bị bắt trong C # không?

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);
}

Tôi muốn nhận được kết quả này:

Nhóm: [Tôi không biết nên vào đây], Giá trị: 123456789 04/09/2009 999
Nhóm: số, Giá trị: 123456789
Nhóm: ngày, Giá trị: 04/09/2009
Nhóm: mã, Giá trị: 999

Câu trả lời:


127

Sử dụng GetGroupNames để lấy danh sách các nhóm trong một biểu thức và sau đó lặp lại các nhóm đó, sử dụng tên làm khóa trong bộ sưu tập nhóm.

Ví dụ,

GroupCollection groups = regex.Match(line).Groups;

foreach (string groupName in regex.GetGroupNames())
{
    Console.WriteLine(
       "Group: {0}, Value: {1}",
       groupName,
       groups[groupName].Value);
}

9
Cảm ơn bạn! Chính xác những gì tôi muốn. Tôi chưa bao giờ nghĩ rằng đây sẽ là trong đối tượng Regex :(
Luiz Damim

22

Cách tốt nhất để làm điều này là sử dụng phương pháp mở rộng này:

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;
    }
}


Khi phương thức tiện ích mở rộng này có sẵn, bạn có thể nhận được các tên và giá trị như sau:

    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"];


7

Bạn nên sử dụng GetGroupNames();và mã sẽ trông giống như sau:

    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);
    }

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.