Regex 생성자
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
Regex 클래스의 새 인스턴스를 초기화합니다.
오버로드
Regex() |
Regex 클래스의 새 인스턴스를 초기화합니다. |
Regex(String) |
지정된 정규 식에 대해 Regex 클래스의 새 인스턴스를 초기화합니다. |
Regex(SerializationInfo, StreamingContext) |
사용되지 않음.
serialize된 데이터를 사용하여 Regex 클래스의 새 인스턴스를 초기화합니다. |
Regex(String, RegexOptions) |
패턴을 수정할 수 있는 옵션을 사용하여 Regex 클래스의 새 인스턴스를 지정된 정규식에 대해 초기화합니다. |
Regex(String, RegexOptions, TimeSpan) |
시간이 초과되기 전에 패턴 일치 메서드가 일치하도록 시도해야 하는 시간을 지정한 패턴과 값을 수정할 수 있는 옵션을 사용하여 Regex 클래스의 새 인스턴스를 지정된 정규식에 대해 초기화하고 컴파일합니다. |
Regex()
Regex(String)
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
지정된 정규 식에 대해 Regex 클래스의 새 인스턴스를 초기화합니다.
public:
Regex(System::String ^ pattern);
public Regex (string pattern);
new System.Text.RegularExpressions.Regex : string -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String)
매개 변수
- pattern
- String
일치 항목을 찾을 정규식 패턴입니다.
예외
정규식 구문 분석 오류가 발생했습니다.
pattern
이(가) null
인 경우
예제
다음 예제에서는 이 생성자를 사용하여 문자 "a" 또는 "t"로 시작하는 단어와 일치하는 정규식을 인스턴스화하는 방법을 보여 줍니다.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b[at]\w+";
string text = "The threaded application ate up the thread pool as it executed.";
MatchCollection matches;
Regex defaultRegex = new Regex(pattern);
// Get matches of pattern in text
matches = defaultRegex.Matches(text);
Console.WriteLine("Parsing '{0}'", text);
// Iterate matches
for (int ctr = 0; ctr < matches.Count; ctr++)
Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
}
}
// The example displays the following output:
// Parsing 'The threaded application ate up the thread pool as it executed.'
// 0. threaded
// 1. application
// 2. ate
// 3. the
// 4. thread
// 5. as
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b[at]\w+"
Dim text As String = "The threaded application ate up the thread pool as it executed."
Dim matches As MatchCollection
Dim defaultRegex As New Regex(pattern)
' Get matches of pattern in text
matches = defaultRegex.Matches(text)
Console.WriteLine("Parsing '{0}'", text)
' Iterate matches
For ctr As Integer = 0 to matches.Count - 1
Console.WriteLine("{0}. {1}", ctr, matches(ctr).Value)
Next
End Sub
End Module
' The example displays the following output:
' Parsing 'The threaded application ate up the thread pool as it executed.'
' 0. threaded
' 1. application
' 2. ate
' 3. the
' 4. thread
' 5. as
비교는 기본적으로 대/소문자를 구분하므로 정규식 패턴은 텍스트의 시작 부분에 있는 "The"라는 단어와 일치할 수 없습니다. 대/소문자를 구분하지 않는 비교의 예는 생성자를 참조 Regex(String, RegexOptions) 하세요.
설명
매개 변수는 pattern
일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식 및 정규식 언어 - 빠른 참조 topics 참조하세요.
Regex(String) 생성자를 호출하는 것은 인수 값이 인 Regex(String, RegexOptions) 생성자를 None 호출하는 options
것과 같습니다.
Regex 개체는 변경할 수 없습니다. 즉, 개체를 만들 때 정의한 일치 패턴에만 사용할 수 있습니다. 그러나 다시 컴파일하지 않고 여러 번 사용할 수 있습니다.
이 생성자는 에 정의된 사전순 문자의 대/소문자 구분 일치를 시도하는 정규식 개체를 pattern
인스턴스화합니다. 대/소문자를 구분하지 않는 일치의 경우 생성자를 사용합니다 Regex.Regex(String, RegexOptions) .
호출자 참고
이 생성자는 Regex 는 만들어진 애플리케이션 도메인의 기본 제한 시간 값을 사용 하는 개체입니다. 애플리케이션 도메인에 대 한 제한 시간 값을 정의 되지 않은 경우는 Regex 값을 사용 하는 개체 InfiniteMatchTimeout, 작업 시간 초과 방지 하는 합니다. 만들기에 대 한 권장 되는 생성자는 Regex 개체가 Regex(String, RegexOptions, TimeSpan), 시간 제한 간격을 설정할 수 있습니다.
추가 정보
적용 대상
Regex(SerializationInfo, StreamingContext)
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
주의
This API supports obsolete formatter-based serialization. It should not be called or extended by application code.
serialize된 데이터를 사용하여 Regex 클래스의 새 인스턴스를 초기화합니다.
protected:
Regex(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Regex (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected Regex (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
Protected Sub New (info As SerializationInfo, context As StreamingContext)
매개 변수
- info
- SerializationInfo
serialize된 패턴과 RegexOptions 정보가 포함된 개체입니다.
- context
- StreamingContext
이 serialization의 대상입니다. 이 매개 변수는 사용되지 않으므로 null
을 지정하세요.
- 특성
예외
정규식 구문 분석 오류가 발생했습니다.
info
에 포함된 패턴이 null
인 경우
info
에 잘못된 RegexOptions 플래그가 포함된 경우
적용 대상
Regex(String, RegexOptions)
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
패턴을 수정할 수 있는 옵션을 사용하여 Regex 클래스의 새 인스턴스를 지정된 정규식에 대해 초기화합니다.
public:
Regex(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public Regex (string pattern, System.Text.RegularExpressions.RegexOptions options);
new System.Text.RegularExpressions.Regex : string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String, options As RegexOptions)
매개 변수
- pattern
- String
일치 항목을 찾을 정규식 패턴입니다.
- options
- RegexOptions
정규식을 수정하는 열거형 값의 비트 조합입니다.
예외
정규식 구문 분석 오류가 발생했습니다.
pattern
이(가) null
인 경우
options
에 잘못된 플래그가 포함된 경우
예제
다음 예제에서는 이 생성자를 사용하여 문자 "a" 또는 "t"로 시작하는 단어와 일치하는 정규식을 인스턴스화하는 방법을 보여 줍니다.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b[at]\w+";
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
string text = "The threaded application ate up the thread pool as it executed.";
MatchCollection matches;
Regex optionRegex = new Regex(pattern, options);
Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString());
// Get matches of pattern in text
matches = optionRegex.Matches(text);
// Iterate matches
for (int ctr = 0; ctr < matches.Count; ctr++)
Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
}
}
// The example displays the following output:
// Parsing 'The threaded application ate up the thread pool as it executed.'
// with options IgnoreCase, Compiled:
// 0. The
// 1. threaded
// 2. application
// 3. ate
// 4. the
// 5. thread
// 6. as
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b[at]\w+"
Dim options As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.Compiled
Dim text As String = "The threaded application ate up the thread pool as it executed."
Dim matches As MatchCollection
Dim optionRegex As New Regex(pattern, options)
Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString())
' Get matches of pattern in text
matches = optionRegex.Matches(text)
' Iterate matches
For ctr As Integer = 0 to matches.Count - 1
Console.WriteLine("{0}. {1}", ctr, matches(ctr).Value)
Next
End Sub
End Module
' The example displays the following output:
' Parsing 'The threaded application ate up the thread pool as it executed.'
' with options IgnoreCase, Compiled:
' 0. The
' 1. threaded
' 2. application
' 3. ate
' 4. the
' 5. thread
' 6. as
일치 컬렉션에는 매개 변수가 대/소문자를 구분하지 않는 비교를 정의했기 때문에 options
텍스트를 시작하는 "The"라는 단어가 포함되어 있습니다.
설명
매개 변수는 pattern
일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식 및 정규식 언어 - 빠른 참조 topics 참조하세요.
Regex 개체는 변경할 수 없습니다. 즉, 개체를 만들 때 정의한 일치 매개 변수에만 사용할 수 있습니다. 그러나 다시 컴파일하지 않고 여러 번 사용할 수 있습니다.
호출자 참고
이 생성자는 Regex 는 만들어진 애플리케이션 도메인의 기본 제한 시간 값을 사용 하는 개체입니다. 애플리케이션 도메인에 대 한 제한 시간 값을 정의 되지 않은 경우는 Regex 값을 사용 하는 개체 InfiniteMatchTimeout, 작업 시간 초과 방지 하는 합니다. 만들기에 대 한 권장 되는 생성자는 Regex 개체가 Regex(String, RegexOptions, TimeSpan), 시간 제한 간격을 설정할 수 있습니다.
추가 정보
적용 대상
Regex(String, RegexOptions, TimeSpan)
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
시간이 초과되기 전에 패턴 일치 메서드가 일치하도록 시도해야 하는 시간을 지정한 패턴과 값을 수정할 수 있는 옵션을 사용하여 Regex 클래스의 새 인스턴스를 지정된 정규식에 대해 초기화하고 컴파일합니다.
public:
Regex(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public Regex (string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
new System.Text.RegularExpressions.Regex : string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String, options As RegexOptions, matchTimeout As TimeSpan)
매개 변수
- pattern
- String
일치 항목을 찾을 정규식 패턴입니다.
- options
- RegexOptions
정규식을 수정하는 열거형 값의 비트 조합입니다.
- matchTimeout
- TimeSpan
시간 제한 간격이거나, 메서드에 시간 제한이 없어야 함을 나타내는 InfiniteMatchTimeout 입니다.
예외
정규식 구문 분석 오류가 발생했습니다.
pattern
이(가) null
인 경우
예제
다음 예제에서는 생성자를 호출 Regex(String, RegexOptions, TimeSpan) 하여 시간 제한 값이 1초인 Regex 개체를 인스턴스화합니다. 줄의 끝에 하나 이상의 "a" 문자가 포함된 하나 이상의 시퀀스와 일치하는 정규식 패턴 (a+)+$
는 과도한 역추적의 대상이 됩니다. 이 RegexMatchTimeoutException throw되는 경우 이 예제에서는 제한 시간 값을 최대 3초 값까지 늘입니다. 그렇지 않으면 패턴과 일치하려는 시도를 중단합니다.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
public class Example
{
const int MaxTimeoutInSeconds = 3;
public static void Main()
{
string pattern = @"(a+)+$"; // DO NOT REUSE THIS PATTERN.
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
Stopwatch sw = null;
string[] inputs= { "aa", "aaaa>",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa>",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>" };
foreach (var inputValue in inputs) {
Console.WriteLine("Processing {0}", inputValue);
bool timedOut = false;
do {
try {
sw = Stopwatch.StartNew();
// Display the result.
if (rgx.IsMatch(inputValue)) {
sw.Stop();
Console.WriteLine(@"Valid: '{0}' ({1:ss\.fffffff} seconds)",
inputValue, sw.Elapsed);
}
else {
sw.Stop();
Console.WriteLine(@"'{0}' is not a valid string. ({1:ss\.fffff} seconds)",
inputValue, sw.Elapsed);
}
}
catch (RegexMatchTimeoutException e) {
sw.Stop();
// Display the elapsed time until the exception.
Console.WriteLine(@"Timeout with '{0}' after {1:ss\.fffff}",
inputValue, sw.Elapsed);
Thread.Sleep(1500); // Pause for 1.5 seconds.
// Increase the timeout interval and retry.
TimeSpan timeout = e.MatchTimeout.Add(TimeSpan.FromSeconds(1));
if (timeout.TotalSeconds > MaxTimeoutInSeconds) {
Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.",
MaxTimeoutInSeconds);
timedOut = false;
}
else {
Console.WriteLine("Changing the timeout interval to {0}",
timeout);
rgx = new Regex(pattern, RegexOptions.IgnoreCase, timeout);
timedOut = true;
}
}
} while (timedOut);
Console.WriteLine();
}
}
}
// The example displays output like the following :
// Processing aa
// Valid: 'aa' (00.0000779 seconds)
//
// Processing aaaa>
// 'aaaa>' is not a valid string. (00.00005 seconds)
//
// Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
// Valid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' (00.0000043 seconds)
//
// Processing aaaaaaaaaaaaaaaaaaaaaa>
// Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 01.00469
// Changing the timeout interval to 00:00:02
// Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 02.01202
// Changing the timeout interval to 00:00:03
// Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 03.01043
// Maximum timeout interval of 3 seconds exceeded.
//
// Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>
// Timeout with 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>' after 03.01018
// Maximum timeout interval of 3 seconds exceeded.
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security
Imports System.Text.RegularExpressions
Imports System.Threading
Module Example
Const MaxTimeoutInSeconds As Integer = 3
Public Sub Main()
Dim pattern As String = "(a+)+$" ' DO NOT REUSE THIS PATTERN.
Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1))
Dim sw As Stopwatch = Nothing
Dim inputs() As String = { "aa", "aaaa>",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaa>",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>" }
For Each inputValue In inputs
Console.WriteLine("Processing {0}", inputValue)
Dim timedOut As Boolean = False
Do
Try
sw = Stopwatch.StartNew()
' Display the result.
If rgx.IsMatch(inputValue) Then
sw.Stop()
Console.WriteLine("Valid: '{0}' ({1:ss\.fffffff} seconds)",
inputValue, sw.Elapsed)
Else
sw.Stop()
Console.WriteLine("'{0}' is not a valid string. ({1:ss\.fffff} seconds)",
inputValue, sw.Elapsed)
End If
Catch e As RegexMatchTimeoutException
sw.Stop()
' Display the elapsed time until the exception.
Console.WriteLine("Timeout with '{0}' after {1:ss\.fffff}",
inputValue, sw.Elapsed)
Thread.Sleep(1500) ' Pause for 1.5 seconds.
' Increase the timeout interval and retry.
Dim timeout As TimeSpan = e.MatchTimeout.Add(TimeSpan.FromSeconds(1))
If timeout.TotalSeconds > MaxTimeoutInSeconds Then
Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.",
MaxTimeoutInSeconds)
timedOut = False
Else
Console.WriteLine("Changing the timeout interval to {0}",
timeout)
rgx = New Regex(pattern, RegexOptions.IgnoreCase, timeout)
timedOut = True
End If
End Try
Loop While timedOut
Console.WriteLine()
Next
End Sub
End Module
' The example displays output like the following:
' Processing aa
' Valid: 'aa' (00.0000779 seconds)
'
' Processing aaaa>
' 'aaaa>' is not a valid string. (00.00005 seconds)
'
' Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
' Valid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' (00.0000043 seconds)
'
' Processing aaaaaaaaaaaaaaaaaaaaaa>
' Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 01.00469
' Changing the timeout interval to 00:00:02
' Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 02.01202
' Changing the timeout interval to 00:00:03
' Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 03.01043
' Maximum timeout interval of 3 seconds exceeded.
'
' Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>
' Timeout with 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>' after 03.01018
' Maximum timeout interval of 3 seconds exceeded.
설명
매개 변수는 pattern
일치시킬 문자열을 상징적으로 설명하는 정규식 언어 요소로 구성됩니다. 정규식에 대한 자세한 내용은 .NET 정규식 및 정규식 언어 - 빠른 참조 topics 참조하세요.
Regex 개체는 변경할 수 없습니다. 즉, 개체를 만들 때 정의하는 일치 패턴에만 사용할 수 있습니다. 그러나 다시 컴파일하지 않고 여러 번 사용할 수 있습니다.
매개 변수는 matchTimeout
패턴 일치 메서드가 시간 초과되기 전에 일치 항목을 찾으려고 시도하는 기간을 지정합니다. 해당 시간 간격에 일치하는 항목이 없으면 패턴 일치 메서드가 예외를 RegexMatchTimeoutException throw합니다. matchTimeout
애플리케이션 도메인에 대해 정의 된 모든 기본 제한 시간 값 재정의 Regex 개체가 만들어집니다. 시간 제한 간격을 관찰 matchTimeout
하는 instance 패턴 일치 메서드에는 다음이 포함됩니다.
제한 시간 간격을 설정하면 거의 일치하는 항목이 포함된 입력을 처리할 때 과도한 역추적에 의존하는 정규식이 응답을 중지하는 것처럼 보이지 않습니다. 자세한 내용은 정규식 및 역추적에 대한 모범 사례를 참조하세요. 적절한 시간 제한 간격을 설정하려면 다음 요소를 고려합니다.
정규식 패턴의 길이 및 복잡성입니다. 더 길고 복잡한 정규식은 더 짧고 간단한 정규식보다 더 많은 시간이 필요합니다.
예상된 컴퓨터 로드입니다. 처리는 CPU 및 메모리 사용률이 높은 시스템에서 더 많은 시간이 걸립니다.
호출자 참고
매개 변수를 matchTimeout
2초와 같은 적절한 값으로 설정하는 것이 좋습니다. 를 지정하여 시간 초과를 사용하지 않도록 설정 InfiniteMatchTimeout하면 정규식 엔진이 약간 더 나은 성능을 제공합니다. 그러나 다음 조건에서만 시간 초과를 사용하지 않도록 설정해야 합니다.
정규식에서 처리된 입력이 알려진 신뢰할 수 있는 원본에서 파생되거나 정적 텍스트로 구성된 경우 사용자가 동적으로 입력한 텍스트는 제외됩니다.
정규식 패턴을 철저히 테스트하여 일치 항목, 비 일치 항목 및 근사 일치 항목을 효율적으로 처리하는지 확인합니다.
정규식 패턴에 거의 일치 항목을 처리할 때 과도한 역추적을 유발하는 것으로 알려진 언어 요소가 없는 경우
추가 정보
적용 대상
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기