'Regular Expressions'에 해당되는 글 1건

  1. 2009.02.08 C# Regular Expressions
2009. 2. 8. 12:57

C# Regular Expressions

출처 : http://wpfkorea.egloos.com/654227

Dos를 사용하던 시절에는 *, !, ?, <>, [] 같은 wildcard 문자를 사용하여 다양한 작업을 했었습니다.
이 방식은 지금도 unix 계열에서는 사랑받는 방식입니다.
그리고 현재도 콘솔에서 프로그램 뒤에 파라미터를 넣는 방식은 널리 사용되고 있습니다. 
정규 표현식은 이런 정의된 문자를 사용해서 패턴을 만들고 그 패턴을 이용해서 원하는 문자를 가져오거나 바꾸는 데 사용되는 방식입니다.

C#에서도 이런 정규 표현식을 작업하기 쉽도록 지원해 줍니다. 그럼 정규 표현식을 지원하는 클래스 들을 알아보겠습니다.
일단 정규 표현식 관련 클래스들은 System.Text.RegularExpressions 에 있습니다.
그리고 System.Text.RegularExpressions 에는 Regex 클래스가 존재합니다.

 Regex 클래스에는 정적 메서드가 여러 개 포합되어 있어서 Regex 개체를 명시적으로 만들지 않고도 정규식을 사용할 수 있습니다.한번 사용한 다음 소멸시킨다는 점에서 정적 메서드를 사용하는 것은 Regex 개체를 만드는 것과 같습니다. Regex 클래스 자체는 스레드로부터 안전하며 읽기 전용으로, 변경할 수 없습니다. , Regex 개체는 모든 스레드에서 만들어질 수 있고 또한 스레드 간에 공유될 수 있으며 관련 메서드는 전역 상태에 전형 영향을 주지 않으면서 모든 스레드에 대해 호출될 수 있습니다. 그러나 Regex 에서 반환하는 Match  MatchCollection 과 같은 결과 개체는 단일 스레드에서만 사용해야 합니다.

 

Regex 클래스에서 자주 사용되는 메서드들은 다음과 같습니다.

l  IsMatch(string) - 정규식이 입력 문자열에서 일치하는 항목을 찾을 것인지 여부를 나타냅니다.

l  Match(string) - 입력 문자열에 정규식이 있는지 검사하고 정확한 결과를 단일 Match 개체로 반환합니다.

l  Matches(string) - Match를 여러 번 호출한 것처럼 입력 문자열에 있는 정규식을 모두 검색하고 성공적인 일치 항목을 모두 반환합니다.

l  Replace(pattern, string) - 정규식에 의해 정의된 문자 패턴이 발견되면 지정된 대체 문자열로 모두 바꿉니다.

l  Split(string, pattern) - 정규식 일치에 의해 정의된 위치에서 부분 문자열로 이루어진 배열로 입력 문자열을 분할합니다.

 

이제 간단한 예제들을 보여 드리겠습니다.

언제나 그러하듯 아래 예제들은 제가 msdn 및 기타 사이트 들에서 긁어온 것들을 살짝 변경하였습니다.

 

IsMatch()  Match() 메서드의 사용법을 알수 있는 예제입니다.
(http://msdn.microsoft.com/ko-kr/library/system.text.regularexpressions.regex_members(VS.80).aspx)

using System;

using System.Text.RegularExpressions;

 

public class Test

{

    public static void Main()

    {

        // 정규 표현식을 정의합니다.

        Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");

 

        // 입력될 스트링을 정의합니다.

        string[] tests = { "-42", "19.99", "0.001", "100 USD" };

 

        // 테스트 코드입니다.

        foreach (string test in tests)

        {

            if (rx.IsMatch(test))           

                Console.WriteLine("{0} is a currency value.", test);           

            else           

                Console.WriteLine("{0} is not a currency value.", test);           

        }

        Console.ReadLine();

    }

}












 

 

이번에도 IsMatch()  Match() 메서드의 사용법을 알수 있는 예제입니다. (http://www.mikesdotnetting.com/Article.aspx?ArticleID=50)

using System;

using System.Text.RegularExpressions;

 

namespace TestCode03

{

    class Program

    {

        static void Main(string[] args)

        {

            string input = "A12";

 

            //Regex 개체를 생성하는 예제입니다.

            //@"[a-z]\d": 알파벳이 나온  integer 형이 나옵니다.

            //RegexOptions.IgnoreCase: 대소문자를 구문하지 않는 옵션입니다.

            Regex re = new Regex(@"[a-z]\d", RegexOptions.IgnoreCase);

            Match m = re.Match(input);

            if (re.IsMatch(input))

            {

                Console.Write(m.Value + "\n");

            }

 

            Console.Write(re.IsMatch(input) + "\n");

 

 

            //정정 메소드인 Regex 생성하지 않는 예제입니다.

            Match m2 = Regex.Match(input, @"[a-z]\d");

            if (Regex.IsMatch(input, @"[a-z]\d"))

            {

                Console.Write(m2.Value + "\n");

            }

 

            Console.Write(Regex.IsMatch(input, @"[a-z]\d") + "\n");

 

            Console.ReadLine();

 

        }

    }

}


 
 

 









MatchCollection
 클래스와 Match 클래스의 사용법을 알수 있는 예제입니다.
(http://msdn.microsoft.com/ko-kr/library/system.text.regularexpressions.regex_members(VS.80).aspx)

using System;

using System.Text.RegularExpressions;

 

public class Test

{

    public static void Main()

    {

        // 반복을 위한 정규 표현식입니다.

        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",

          RegexOptions.Compiled | RegexOptions.IgnoreCase);

 

        // 입력되는 문자열입니다.      

        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

 

        // 일치하는 문자열을 찾습니다.

        MatchCollection matches = rx.Matches(text);

 

        // 표현식과 일치하는 문자열의 갯수를 나타냅니다.

        Console.WriteLine("{0} matches found.", matches.Count);

 

        // 일치한 문자열을 표시합니다.

        foreach (Match match in matches)

        {

            string word = match.Groups["word"].Value;

            int index = match.Index;

            Console.WriteLine("{0} repeated at position {1}", word, index);

        }

        Console.ReadLine();

    }

}


 








 

MatchCollection 클래스와 Match 클래스의 사용법을 알수 있는 예제입니다.
(http://www.mikesdotnetting.com/Article.aspx?ArticleID=50)

using System;

using System.Text.RegularExpressions;

 

namespace TestCode04

{

    class Program

    {

        static void Main(string[] args)

        {

            string input = "A12 B34 C56 D78";

 

            //Regex 개체를 생성합니다.

            Regex re = new Regex(@"[a-z]\d", RegexOptions.IgnoreCase);

            MatchCollection mc = re.Matches(input);

            foreach (Match mt in mc)

            {

                Console.Write(mt.ToString() + "\n");

            }

            Console.Write(mc.Count.ToString() + "\n");

 

 

            //Regex 정적클래스 이므로 개체를 생성하지 않아도 됩니다.

            MatchCollection mc2 = Regex.Matches(input, @"[a-z]\d", RegexOptions.IgnoreCase);

            foreach (Match mt in mc)

            {

                Console.Write(mt.ToString() + "\n");

            }

            Console.Write(mc2.Count.ToString() + "\n");

 

            Console.ReadLine();

        }

    }

}


 



















Replace
메서드의 사용법을 알수 있는 예제입니다. 알파벳을 “XX”로 변환합니다.

using System;

using System.Text.RegularExpressions;

 

namespace TestCode05

{

    class Program

    {

        static void Main(string[] args)

        {

            string input = @"A12 B34 C56 D78 E12 F34 G56 H78";

 

            //Regex 개체 생성

            Regex re = new Regex(@"[a-z]\d", RegexOptions.IgnoreCase);

            string newString = re.Replace(input, "XX");

            Console.Write(newString);

 

            //Regex 개체를생성하지 않아도 됩니다.

            string newString2 = Regex.Replace(input, @"[A-Z]\d", "XX");

            Console.Write(newString2);

 

            Console.ReadLine();

        }

    }

} 


 

 









Split
메서드의 사용법을 알수 있는 예제입니다. 알파벳을 “XX”로 변환합니다.

using System;

using System.Text.RegularExpressions;

 

namespace TestCode06

{

    class Program

    {

        static void Main(string[] args)

        {

            string input = "AB1 DE2 FG3 HI4 JK5 LM6 NO7 PQ8 RS9";

 

            //Regex 개체 생성

            Regex re = new Regex(@"\s");

            string[] parts = re.Split(input);

            foreach (string part in parts)

            {

                Console.Write(part + "\n");

            }

 

            //Regex 개체를생성하지 않아도 됩니다. 스페이스를 기준으로 문자열을 분할합니다.

            string[] parts2 = Regex.Split(input, @"\s");

            foreach (string part2 in parts2)

            {

                Console.Write(part2 + "\n");

            }

 

            Console.ReadLine();

 

        }

    }

}


 

 

 
























End.