정규식은 텍스트를 처리하는 강력하고 유연하며 효율적인 방법을 제공합니다. 정규식의 광범위한 패턴 일치 표기법을 사용하면 대량의 텍스트를 신속하게 구문 분석하여 다음을 수행할 수 있습니다.
- 특정 문자 패턴을 찾습니다.
- 텍스트의 유효성을 검사하여 미리 정의된 패턴(예: 전자 메일 주소)과 일치하는지 확인합니다.
- 텍스트 하위 문자열을 추출, 편집, 바꾸기 또는 삭제합니다.
- 보고서를 생성하기 위해 추출된 문자열을 컬렉션에 추가합니다.
문자열을 처리하거나 큰 텍스트 블록을 구문 분석하는 많은 애플리케이션에서 정규식은 필수 도구입니다.
정규식의 작동 방식
정규식을 사용한 텍스트 처리의 중심은 .NET의 System.Text.RegularExpressions.Regex 개체로 표현되는 정규식 엔진입니다. 최소한 정규식을 사용하여 텍스트를 처리하려면 정규식 엔진에 다음 두 가지 정보 항목이 제공되어야 합니다.
텍스트에서 식별할 정규식 패턴입니다.
.NET에서 정규식 패턴은 Perl 5 정규식과 호환되는 특수 구문 또는 언어로 정의되며 오른쪽에서 왼쪽 일치와 같은 몇 가지 추가 기능을 추가합니다. 자세한 내용은 정규식 언어 - 빠른 참조참조하세요.
정규식 패턴을 위한 구문 분석 텍스트입니다.
Regex 클래스의 메서드를 사용하면 다음 작업을 수행할 수 있습니다.
Regex.IsMatch 메서드를 호출하여 입력 텍스트에서 정규식 패턴이 발생하는지 여부를 확인합니다. IsMatch 메서드를 사용하여 텍스트의 유효성을 검사하는 예제는 방법: 문자열이 유효한 전자 메일 형식인지 확인.
Regex.Match 또는 Regex.Matches 메서드를 호출하여 정규식 패턴과 일치하는 텍스트를 하나 또는 모두 검색합니다. 이전 메서드는 일치하는 텍스트에 대한 정보를 제공하는 System.Text.RegularExpressions.Match 개체를 반환합니다. 후자는 구문 분석된 텍스트에 있는 각 일치 항목에 대해 하나의 MatchCollection 개체를 포함하는 System.Text.RegularExpressions.Match 개체를 반환합니다.
Regex.Replace 메서드를 호출하여 정규식 패턴과 일치하는 텍스트를 바꿉다. Replace 메서드를 사용하여 날짜 서식을 변경하고 문자열에서 잘못된 문자를 제거하는 예제는 방법: 문자열 잘못된 문자 제거 및 예제: 날짜 서식 변경참조하세요.
정규식 개체 모델에 대한 개요는 정규식 개체 모델참조하세요.
정규식 언어에 대한 자세한 내용은 정규식 언어 - 빠른 참조 참조하거나 다음 브로셔 중 하나를 다운로드하여 인쇄합니다.
정규식 예제
String 클래스에는 더 큰 문자열에서 리터럴 문자열을 찾으려는 경우 사용할 수 있는 문자열 검색 및 대체 메서드가 포함됩니다. 정규식은 더 큰 문자열에서 여러 부분 문자열 중 하나를 찾으려는 경우 또는 다음 예제와 같이 문자열의 패턴을 식별하려는 경우에 가장 유용합니다.
경고
System.Text.RegularExpressions를 사용하여 신뢰할 수 없는 입력을 처리하는 경우 시간 제한을 전달합니다. 악의적인 사용자가 RegularExpressions
입력을 제공하여 서비스 거부 공격일으킬 수 있습니다.
RegularExpressions
를 사용하는 ASP.NET Core Framework API는 시간 제한을 전달합니다.
팁 (조언)
System.Web.RegularExpressions 네임스페이스에는 HTML, XML 및 ASP.NET 문서에서 문자열을 구문 분석하기 위해 미리 정의된 정규식 패턴을 구현하는 여러 정규식 개체가 포함되어 있습니다. 예를 들어 TagRegex 클래스는 문자열의 시작 태그를 식별하고 CommentRegex 클래스는 문자열의 ASP.NET 주석을 식별합니다.
예제 1: 부분 문자열 바꾸기
메일링 목록에 이름 및 성과 함께 제목(Mr., Mrs., Miss 또는 Ms.)이 포함된 이름이 포함되어 있다고 가정합니다. 목록에서 봉투 레이블을 생성할 때 제목을 포함하지 않으려는 경우를 가정해 보겠습니다. 이 경우 다음 예제와 같이 정규식을 사용하여 제목을 제거할 수 있습니다.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = "(Mr\\.? |Mrs\\.? |Miss |Ms\\.? )";
string[] names = { "Mr. Henry Hunt", "Ms. Sara Samuels",
"Abraham Adams", "Ms. Nicole Norris" };
foreach (string name in names)
Console.WriteLine(Regex.Replace(name, pattern, String.Empty));
}
}
// The example displays the following output:
// Henry Hunt
// Sara Samuels
// Abraham Adams
// Nicole Norris
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(Mr\.? |Mrs\.? |Miss |Ms\.? )"
Dim names() As String = {"Mr. Henry Hunt", "Ms. Sara Samuels", _
"Abraham Adams", "Ms. Nicole Norris"}
For Each name As String In names
Console.WriteLine(Regex.Replace(name, pattern, String.Empty))
Next
End Sub
End Module
' The example displays the following output:
' Henry Hunt
' Sara Samuels
' Abraham Adams
' Nicole Norris
정규식 패턴 (Mr\.? |Mrs\.? |Miss |Ms\.? )
은 "Mr ", "Mr. ", "Mrs ", "Mrs. ", "Miss ", "Ms ", 또는 "Ms. "에 해당하는 모든 경우를 찾습니다.
Regex.Replace 메서드에 대한 호출은 일치하는 문자열을 String.Empty; 로 바꿉니다. 즉, 원래 문자열에서 제거합니다.
예제 2: 중복 단어 식별
실수로 단어를 복제하는 것은 작성자가 만드는 일반적인 오류입니다. 다음 예제와 같이 정규식을 사용하여 중복된 단어를 식별합니다.
using System;
using System.Text.RegularExpressions;
public class Class1
{
public static void Main()
{
string pattern = @"\b(\w+?)\s\1\b";
string input = "This this is a nice day. What about this? This tastes good. I saw a a dog.";
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
Console.WriteLine($"{match.Value} (duplicates '{match.Groups[1].Value}') at position {match.Index}");
}
}
// The example displays the following output:
// This this (duplicates 'This') at position 0
// a a (duplicates 'a') at position 66
Imports System.Text.RegularExpressions
Module modMain
Public Sub Main()
Dim pattern As String = "\b(\w+?)\s\1\b"
Dim input As String = "This this is a nice day. What about this? This tastes good. I saw a a dog."
For Each match As Match In Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
Console.WriteLine("{0} (duplicates '{1}') at position {2}", _
match.Value, match.Groups(1).Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
' This this (duplicates 'This') at position 0
' a a (duplicates 'a') at position 66
정규식 패턴 \b(\w+?)\s\1\b
다음과 같이 해석할 수 있습니다.
패턴 | 해석 |
---|---|
\b |
시작점은 단어 경계에서입니다. |
(\w+?) |
하나 이상의 단어 문자를 가능한 한 적게 일치시킵니다. 함께 \1 라고 할 수 있는 그룹을 형성합니다. |
\s |
공백 문자를 일치시킵니다. |
\1 |
이름이 \1 인 그룹에 해당하는 부분 문자열과 일치합니다. |
\b |
단어 경계를 찾습니다. |
Regex.Matches 메서드는 정규식 옵션을 RegexOptions.IgnoreCase설정하여 호출됩니다. 따라서 일치 작업은 대/소문자를 구분하지 않으며, 이 예제에서는 부분 문자열 "This this"를 중복으로 식별합니다.
입력 문자열에 "this?"라는 하위 문자열이 포함되어 있습니까? 이". 그러나 중간 문장 부호 때문에 중복으로 식별되지 않습니다.
예제 3: 문화권 구분 정규식을 동적으로 빌드
다음 예제는 .NET의 세계화 기능이 제공하는 유연성과 결합된 정규식의 강력한 기능을 보여 줍니다. NumberFormatInfo 개체를 사용하여 시스템의 현재 문화권에서 통화 값의 형식을 결정합니다. 그런 다음 해당 정보를 사용하여 텍스트에서 통화 값을 추출하는 정규식을 동적으로 생성합니다. 각 일치 항목에 대해 숫자 문자열만 포함된 하위 그룹을 추출하고, Decimal 값으로 변환하고, 실행 합계를 계산합니다.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
// Define text to be parsed.
string input = "Office expenses on 2/13/2008:\n" +
"Paper (500 sheets) $3.95\n" +
"Pencils (box of 10) $1.00\n" +
"Pens (box of 10) $4.49\n" +
"Erasers $2.19\n" +
"Ink jet printer $69.95\n\n" +
"Total Expenses $ 81.58\n";
// Get current culture's NumberFormatInfo object.
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
// Assign needed property values to variables.
string currencySymbol = nfi.CurrencySymbol;
bool symbolPrecedesIfPositive = nfi.CurrencyPositivePattern % 2 == 0;
string groupSeparator = nfi.CurrencyGroupSeparator;
string decimalSeparator = nfi.CurrencyDecimalSeparator;
// Form regular expression pattern.
string pattern = Regex.Escape( symbolPrecedesIfPositive ? currencySymbol : "") +
@"\s*[-+]?" + "([0-9]{0,3}(" + groupSeparator + "[0-9]{3})*(" +
Regex.Escape(decimalSeparator) + "[0-9]+)?)" +
(! symbolPrecedesIfPositive ? currencySymbol : "");
Console.WriteLine( "The regular expression pattern is:");
Console.WriteLine(" " + pattern);
// Get text that matches regular expression pattern.
MatchCollection matches = Regex.Matches(input, pattern,
RegexOptions.IgnorePatternWhitespace);
Console.WriteLine($"Found {matches.Count} matches.");
// Get numeric string, convert it to a value, and add it to List object.
List<decimal> expenses = new List<Decimal>();
foreach (Match match in matches)
expenses.Add(Decimal.Parse(match.Groups[1].Value));
// Determine whether total is present and if present, whether it is correct.
decimal total = 0;
foreach (decimal value in expenses)
total += value;
if (total / 2 == expenses[expenses.Count - 1])
Console.WriteLine($"The expenses total {expenses[expenses.Count - 1]:C2}.");
else
Console.WriteLine($"The expenses total {total:C2}.");
}
}
// The example displays the following output:
// The regular expression pattern is:
// \$\s*[-+]?([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?)
// Found 6 matches.
// The expenses total $81.58.
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Text.RegularExpressions
Public Module Example
Public Sub Main()
' Define text to be parsed.
Dim input As String = "Office expenses on 2/13/2008:" + vbCrLf + _
"Paper (500 sheets) $3.95" + vbCrLf + _
"Pencils (box of 10) $1.00" + vbCrLf + _
"Pens (box of 10) $4.49" + vbCrLf + _
"Erasers $2.19" + vbCrLf + _
"Ink jet printer $69.95" + vbCrLf + vbCrLf + _
"Total Expenses $ 81.58" + vbCrLf
' Get current culture's NumberFormatInfo object.
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
' Assign needed property values to variables.
Dim currencySymbol As String = nfi.CurrencySymbol
Dim symbolPrecedesIfPositive As Boolean = CBool(nfi.CurrencyPositivePattern Mod 2 = 0)
Dim groupSeparator As String = nfi.CurrencyGroupSeparator
Dim decimalSeparator As String = nfi.CurrencyDecimalSeparator
' Form regular expression pattern.
Dim pattern As String = Regex.Escape(CStr(IIf(symbolPrecedesIfPositive, currencySymbol, ""))) + _
"\s*[-+]?" + "([0-9]{0,3}(" + groupSeparator + "[0-9]{3})*(" + _
Regex.Escape(decimalSeparator) + "[0-9]+)?)" + _
CStr(IIf(Not symbolPrecedesIfPositive, currencySymbol, ""))
Console.WriteLine("The regular expression pattern is: ")
Console.WriteLine(" " + pattern)
' Get text that matches regular expression pattern.
Dim matches As MatchCollection = Regex.Matches(input, pattern, RegexOptions.IgnorePatternWhitespace)
Console.WriteLine("Found {0} matches. ", matches.Count)
' Get numeric string, convert it to a value, and add it to List object.
Dim expenses As New List(Of Decimal)
For Each match As Match In matches
expenses.Add(Decimal.Parse(match.Groups.Item(1).Value))
Next
' Determine whether total is present and if present, whether it is correct.
Dim total As Decimal
For Each value As Decimal In expenses
total += value
Next
If total / 2 = expenses(expenses.Count - 1) Then
Console.WriteLine("The expenses total {0:C2}.", expenses(expenses.Count - 1))
Else
Console.WriteLine("The expenses total {0:C2}.", total)
End If
End Sub
End Module
' The example displays the following output:
' The regular expression pattern is:
' \$\s*[-+]?([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?)
' Found 6 matches.
' The expenses total $81.58.
현재 문화 설정이 영어(미국)(en-US)인 컴퓨터에서, 이 예는 정규 표현식 \$\s*[-+]?([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?)
을 동적으로 작성합니다. 이 정규식 패턴은 다음과 같이 해석할 수 있습니다.
패턴 | 해석 |
---|---|
\$ |
입력 문자열에서 달러 기호($ )의 단일 항목을 찾습니다. 정규식 패턴 문자열에는 달러 기호가 정규식 앵커가 아닌 문자 그대로 해석되어야 함을 나타내는 백슬래시를 포함합니다.
$ 기호만으로 정규식 엔진이 문자열의 끝에서 일치를 시작해야 함을 나타냅니다. 현재 문화권의 통화 기호가 정규식 기호로 잘못 해석되지 않도록 하기 위해 예제에서는 Regex.Escape 메서드를 호출하여 문자를 이스케이프합니다. |
\s* |
공백 문자가 0개 이상 포함되어 있는지 찾습니다. |
[-+]? |
양수 또는 음수 부호가 0개 또는 1개 있는지를 찾습니다. |
([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?) |
외부 괄호는 이 식을 캡처링 그룹 또는 하위 식으로 정의합니다. 일치 항목이 발견되면 일치하는 문자열의 이 부분에 대한 정보를 Group 속성에서 반환된 GroupCollection 개체의 두 번째 Match.Groups 개체에서 검색할 수 있습니다. 컬렉션의 첫 번째 요소는 전체 일치를 나타냅니다. |
[0-9]{0,3} |
0에서 9까지의 소수 자릿수를 0~3번 찾습니다. |
(,[0-9]{3})* |
0개 이상의 그룹 구분 기호에 이어지는 세 자리 숫자를 찾습니다. |
\. |
소수 구분 기호가 한 번만 나타나는 경우를 찾으세요. |
[0-9]+ |
하나 이상의 소수 자릿수를 찾습니다. |
(\.[0-9]+)? |
소수 구분 기호가 0개 또는 1개, 10진수 이상인 경우를 찾습니다. |
입력 문자열 내에 각 하위 패턴이 있으면 일치 성공이며, 일치에 대한 정보를 포함하는 Match 개체가 MatchCollection 개체에 추가됩니다.
관련 문서
제목 | 설명 |
---|---|
정규식 언어 - 빠른 참조 | 정규식을 정의하는 데 사용할 수 있는 문자, 연산자 및 구문 집합에 대한 정보를 제공합니다. |
정규 표현식 객체 모델 | 정규식 클래스를 사용하는 방법을 보여 주는 정보 및 코드 예제를 제공합니다. |
정규식 동작에 대한 의 세부 정보 | .NET 정규식의 기능 및 동작에 대한 정보를 제공합니다. |
Visual Studio에서 정규식 사용 |
참고 문헌
.NET