IT story

C # Regex에서 캡처 된 그룹의 이름을 어떻게 얻습니까?

hot-time 2020. 8. 28. 08:04
반응형

C # Regex에서 캡처 된 그룹의 이름을 어떻게 얻습니까?


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

이 결과를 얻고 싶습니다.

그룹 : [무엇을 가야할지 모르겠습니다.], 값 : 123456789 04/09/2009 999
그룹 : 숫자, 값 : 123456789
그룹 : 날짜, 값 : 2009 년 4 월 9 일
그룹 : 코드, 값 : 999

GetGroupNames사용 하여 식에서 그룹 목록을 가져온 다음 이름을 그룹 컬렉션에 대한 키로 사용하여 반복합니다.

예를 들면

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

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

이를위한 가장 깨끗한 방법은 다음 확장 방법을 사용하는 것입니다.

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


이 확장 방법이 제자리에 있으면 다음과 같은 이름과 값을 얻을 수 있습니다.

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

사용해야 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);
    }

.NET 4.7부터 사용 가능한Group.Name 속성이 있습니다 .


Regex 클래스가 이것의 핵심입니다!

foreach(Group group in match.Groups)
{
    Console.WriteLine("Group: {0}, Value: {1}", regex.GroupNameFromNumber(group.Index), group.Value);
}

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.groupnamefromnumber.aspx

참고URL : https://stackoverflow.com/questions/1381097/how-do-i-get-the-name-of-captured-groups-in-a-c-sharp-regex

반응형