Regex 建構函式
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
初始化 Regex 類別的新執行個體。
多載
| 名稱 | Description |
|---|---|
| Regex() |
初始化 Regex 類別的新執行個體。 |
| Regex(String) |
初始化該類別的新實例 Regex ,以初始化指定的正規表達式。 |
| Regex(SerializationInfo, StreamingContext) |
已淘汰.
透過序列化資料初始化該類別的新實例 Regex 。 |
| Regex(String, RegexOptions) |
初始化該類別的新實例 Regex ,並以修改模式的選項。 |
| Regex(String, RegexOptions, TimeSpan) |
初始化該類別的新實例 Regex ,針對指定的正則表達式,並加入修改模式的選項,以及一個值,指定模式匹配方法應嘗試匹配多久後才會逾時。 |
Regex(String)
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- 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 正則表達式 及 正則表達式語言 - 快速參考主題。
呼叫Regex(String)建構子等同於以參數值為 Regex(String, RegexOptions)None 的呼叫建構子。options
物件 Regex 是不可變的,意思是它只能用於你創建時定義的匹配模式。 然而,它可以無限次使用而無需重新編譯。
此建構子實例化一個正則表達式物件,嘗試對定義於 中的 pattern任意字母進行大小寫區分匹配。 對於大小寫不區分的匹配,請使用 Regex.Regex(String, RegexOptions) 構造子。
給呼叫者的注意事項
此建構子會建立一個 Regex 物件,使用該應用程式域的預設逾時值。 若應用程式域未定義逾時值, Regex 物件會使用該值 InfiniteMatchTimeout,以防止操作逾時。建議建立物件的建構器 Regex 是 Regex(String, RegexOptions, TimeSpan),它讓你可以設定逾時間隔。
另請參閱
適用於
Regex(SerializationInfo, StreamingContext)
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
警告
This API supports obsolete formatter-based serialization. It should not be called or extended by application code.
透過序列化資料初始化該類別的新實例 Regex 。
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);
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}")>]
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
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
包含序列化模式與 RegexOptions 資訊的物件。
- context
- StreamingContext
此連載的目的地。 (此參數未被使用;請說明 null。)
- 屬性
例外狀況
發生正則表達式剖析錯誤。
包含 的模式 info 為 null。
info 包含一個無效 RegexOptions 旗標。
不支援物件序列 Regex 化。
適用於
Regex(String, RegexOptions)
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- 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 不是一個有效的 RegexOptions 值。
範例
以下範例說明如何使用此構造子實例化一個正則表達式,該表達式能匹配任何以「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
請注意,匹配集合包含了開頭的「The」一詞,因為該 options 參數有定義大小寫不區分的比較。
備註
參數 pattern 由正則表達式語言元素組成,符號性地描述相符的字串。 欲了解更多正則表達式資訊,請參閱 .NET 正則表達式 及 正則表達式語言 - 快速參考主題。
物件 Regex 是不可變的,意思是它只能用於你建立時定義的匹配參數。 然而,它可以無限次使用而無需重新編譯。
給呼叫者的注意事項
此建構子會建立一個 Regex 物件,使用該應用程式域的預設逾時值。 若應用程式域未定義逾時值, Regex 物件會使用該值 InfiniteMatchTimeout,以防止操作逾時。建議建立物件的建構器 Regex 是 Regex(String, RegexOptions, TimeSpan),它讓你可以設定逾時間隔。
另請參閱
適用於
Regex(String, RegexOptions, TimeSpan)
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- Regex.cs
- 來源:
- 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。
options 不是一個有效的 RegexOptions 數值,或 matchTimeout 為負數、零值,或大於約24天。
範例
以下範例呼叫建 Regex(String, RegexOptions, TimeSpan) 構子實例 Regex 化一個逾時值為一秒的物件。 正則表達式模式 (a+)+$,即與一行末尾一個或多個「a」字元序列匹配,容易受到過度回溯的影響。 若擲出 a RegexMatchTimeoutException ,該範例將超時值增加至最大三秒。 否則,它就放棄了對應模式的嘗試。
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 正則表達式 及 正則表達式語言 - 快速參考主題。
物件 Regex 是不變的,意思是它只能用於你創建時所定義的匹配模式。 然而,它可以無限次使用而無需重新編譯。
參數 matchTimeout 指定模式匹配方法應該嘗試尋找匹配的時間長短,直到逾時結束。若在該時間區間內未找到匹配,模式匹配方法會拋 RegexMatchTimeoutException 出例外。
matchTimeout 覆蓋物件所建立的應用程式域 Regex 所定義的任何預設逾時值。 觀察逾時區間的 matchTimeout 實例模式匹配方法包括以下幾種:
設定逾時間隔可防止依賴過度回溯的正則表達式在處理包含接近匹配的輸入時似乎停止回應。 欲了解更多資訊,請參閱《 正則表達 式與 回溯的最佳實務》。 為了設定合理的超時間隔,請考慮以下因素:
正則表達式模式的長度與複雜度。 較長且複雜的正則表達式需要更多時間,而較短且簡單的則則是如此。
預期的機器負載。 在CPU和記憶體使用率高的系統上,處理時間會比較多。
給呼叫者的注意事項
我們建議你將參數設定 matchTimeout 為適當的值,例如兩秒。 如果你指定 InfiniteMatchTimeout,則會讓 停止,正則表達式引擎的效能會稍微好一點。 不過,您應該只在下列情況下停用逾時:
正則表達式所處理的輸入衍生自已知且受信任的來源,或包含靜態文字時。 這會排除使用者動態輸入的文字。
當正則表達式模式經過徹底測試,以確保其有效率地處理相符專案、不相符專案和接近相符專案時。
當正則表達式模式不包含任何已知在處理接近相符專案時造成過度回溯的語言元素。