-
Regex 정규식 활용 그룹명.NET/Common 2022. 9. 7. 13:11
static void Main(string[] args) { Regex regex = new Regex(@"^(?<test>.+?)_(?<pid>.+)\..+$"); var match = regex.Match("TEST_PID12345678.csv"); Dictionary<string, string> keyValues = new Dictionary<string, string>(); if(match.Success) { foreach (string groupName in regex.GetGroupNames()) { if (char.IsDigit(groupName.ToCharArray()[0])) continue; //숫자로 그룹명 자동생성 keyValues.Add(groupName, match.Groups[groupName].Value); } Console.WriteLine(keyValues["test"]); Console.WriteLine(keyValues["pid"]); } else { Console.WriteLine("정규식에 맞지 않는 텍스트"); } Console.ReadKey(); }
Regex 생성자에 들어가는 문자열이 Regex 패턴입니다. regex 객체 생성이후
regex.Match(판독텍스트)로 판독을 실행한다. 판독 대상 문자와 패턴이 복잡해질수록 판독시간은 길어집니다.
(?<GruopName>(규칙))과 같은형식으로 판독텍스트와 치환하여 사용 할수 있습니다.
단 match.Groups에는 자동생성되는 숫자형 그룹명의 그룹들도 있을수 있습니다.
위와 같은 방법으로 특정 문자열에서 원하는 일부의 문자열만 가져올 수 있으나 판독 대상 문자열의 길이가 긴 경우 문제가 됩니다. 모든 데이터를 몰아넣은 csv 파일과 같은 곳에서 사용하면 문제가 될 수 있습니다.
'.NET > Common' 카테고리의 다른 글
C# .NET 솔루션, 프로젝트 구조 (0) 2025.02.23 C# 문법 Null Safety (0) 2022.09.17 C# RS232 통신 (0) 2022.09.04