반응형
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);
}
반응형
'IT story' 카테고리의 다른 글
텍스트 상자에서 Enter를 누를 때 HTML 버튼을 트리거하는 방법은 무엇입니까? (0) | 2020.08.29 |
---|---|
TwoWay 또는 OneWayToSource 바인딩은 읽기 전용 속성에서 작동 할 수 없습니다. (0) | 2020.08.28 |
JavaFX 및 OpenJDK (0) | 2020.08.28 |
matplotlib는 ylim 값을 얻습니다. (0) | 2020.08.28 |
모바일 사파리에서 뷰포트 메타 태그를 즉시 변경할 수 있습니까? (0) | 2020.08.28 |