정규식(Regular Expression)은 입력 텍스트와 비교해 일치 여부를 검사할 수 있는 패턴을 의미합니다. .NET 프레임워크는 이러한 패턴 매칭을 수행할 수 있는 강력한 정규식 엔진을 내장하고 있어, 별도의 외부 라이브러리 없이 문자열 검색·치환·분할 작업을 손쉽게 처리할 수 있습니다.
하나의 패턴은 하나 이상의 문자 리터럴, 연산자, 또는 구문(constructor)으로 구성됩니다. 예를 들어 'S'로 시작하는 단어를 찾고 싶다면 다음과 같이 C#의 정규식을 활용할 수 있습니다.
예제 코드
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "Email Sent Today!";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}실행 결과
Matching words that start with 'S': The Expression: \bS\S* Sent
위 예제에서 사용된 패턴 \bS\S*를 살펴보면, \b는 단어 경계(word boundary)를 의미하고, S는 문자 'S'로 시작함을, \S*는 공백이 아닌 문자가 0개 이상 이어짐을 나타냅니다. 따라서 입력 문자열 중 'Sent'만 매칭 결과로 출력됩니다.
C# Regex 클래스의 주요 메서드
C#에서 정규식을 다룰 때 사용하는 Regex 클래스는 다음과 같은 대표적인 메서드를 제공합니다.
| 번호 | 메서드 및 설명 |
|---|---|
| 1 | public bool IsMatch(string input) Regex 생성자에 지정된 정규식이 입력 문자열에서 하나라도 일치하는지 여부를 반환합니다. |
| 2 | public bool IsMatch(string input, int start) 입력 문자열의 지정된 시작 위치부터 검사를 시작하여, 정규식과 일치하는 부분이 있는지 여부를 반환합니다. |
| 3 | public static bool IsMatch(string input, string pattern) 지정된 정규식 패턴이 입력 문자열에서 일치하는지 여부를 반환합니다. 인스턴스 생성 없이 바로 호출할 수 있는 정적 메서드입니다. |
| 4 | public MatchCollection Matches(string input) 입력 문자열 전체를 검색하여 정규식과 일치하는 모든 항목을 MatchCollection 형태로 반환합니다. |
| 5 | public string Replace(string input, string replacement) 입력 문자열에서 정규식 패턴과 일치하는 모든 부분을 지정된 대체 문자열로 치환합니다. |
| 6 | public string[] Split(string input) Regex 생성자에 지정된 정규식 패턴이 나타나는 위치를 기준으로 입력 문자열을 분할하여, 부분 문자열 배열로 반환합니다. |