.NET/Common

Regex 정규식 활용 그룹명

atawlee 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 파일과 같은 곳에서 사용하면 문제가 될 수 있습니다.