.NET 中的正則表示式包含三種其他語言建構。 其中一個可讓您啟用或停用正則表達式模式中間的特定比對選項。 其餘兩個可讓您在正則表達式中包含註解。
內嵌選項
您可以使用語法,為正則表達式的一部分設定或停用特定模式比對選項
(?imnsx-imnsx)
您可以列出要在問號之後啟用的選項,以及要在減號之後停用的選項。 下表會說明每個選項。 如需每個選項的詳細資訊,請參閱 正則表示式選項。
| 選項 | 說明 |
|---|---|
i |
不區分大小寫的比對。 |
m |
多行模式。 |
n |
僅限明確擷取 (括弧不作為擷取群組。) |
s |
單行模式。 |
x |
忽略未逸出的空白字元,並允許 x 模式的註釋。 |
定義為 (?imnsx-imnsx) 的正則表達式選項的任何變更會持續生效,直到封閉群組的結尾。
備註
(?imnsx-imnsx:
子表達式)群組建構提供子表達式的相同功能。 如需詳細資訊,請參閱群組建構。
下列範例會使用 i、 n和 x 選項來啟用不區分大小寫和明確擷取,並忽略正則表達式中間正則表達式模式中的空格符。
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern;
string input = "double dare double Double a Drooling dog The Dreaded Deep";
pattern = @"\b(D\w+)\s(d\w+)\b";
// Match pattern using default options.
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine($" Group {ctr}: {match.Groups[ctr].Value}");
}
Console.WriteLine();
// Change regular expression pattern to include options.
pattern = @"\b(D\w+)(?ixn) \s (d\w+) \b";
// Match new pattern with options.
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine($" Group {ctr}: '{match.Groups[ctr].Value}'");
}
}
}
// The example displays the following output:
// Drooling dog
// Group 1: Drooling
// Group 2: dog
//
// Drooling dog
// Group 1: 'Drooling'
// Dreaded Deep
// Group 1: 'Dreaded'
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String
Dim input As String = "double dare double Double a Drooling dog The Dreaded Deep"
pattern = "\b(D\w+)\s(d\w+)\b"
' Match pattern using default options.
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
If match.Groups.Count > 1 Then
For ctr As Integer = 1 To match.Groups.Count - 1
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups(ctr).Value)
Next
End If
Next
Console.WriteLine()
' Change regular expression pattern to include options.
pattern = "\b(D\w+)(?ixn) \s (d\w+) \b"
' Match new pattern with options.
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
If match.Groups.Count > 1 Then
For ctr As Integer = 1 To match.Groups.Count - 1
Console.WriteLine(" Group {0}: '{1}'", ctr, match.Groups(ctr).Value)
Next
End If
Next
End Sub
End Module
' The example displays the following output:
' Drooling dog
' Group 1: Drooling
' Group 2: dog
'
' Drooling dog
' Group 1: 'Drooling'
' Dreaded Deep
' Group 1: 'Dreaded'
此範例會定義兩個正則表達式。 第一個 \b(D\w+)\s(d\w+)\b 會匹配兩個連續單字,它們分別以大寫「D」和小寫「d」開頭。 第二個正則表示式 \b(D\w+)(?ixn) \s (d\w+) \b會使用內嵌選項來修改此模式,如下表所述。 透過比較結果來確認(?ixn)構件的效果。
| 樣式 | 說明 |
|---|---|
\b |
從單字分界開始。 |
(D\w+) |
比對一個大寫的「D」後面接著一或多個字元。 這是第一個擷取群組。 |
(?ixn) |
從現在開始,比較不區分大小寫、只進行明確擷取,並忽略正則表達式中的空白。 |
\s |
比對空白字符。 |
(d\w+) |
比對大寫或小寫「d」後面接著一或多個單詞字符。 未擷取此群組,因為 n 已啟用 [明確擷取] 選項。 |
\b |
比對字邊界。 |
內嵌註解
(?#
註解) 建構可讓您在正則表達式中包含內嵌註解。 正則表達式引擎不會在模式比對中使用批注的任何部分,不過批註會包含在方法傳 Regex.ToString 回的字串中。 批注會在第一個右括號結束。
下列範例會從上一節中的範例重複第一個正則表達式模式。 它會在正則表達式中新增兩個內嵌註解,以指示比較是否區分大小寫。 正則表達式模式 \b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comparison)d\w+)\b的定義如下。
| 樣式 | 說明 |
|---|---|
\b |
從單字分界開始。 |
(?# case-sensitive comparison) |
註解。 這不會影響模式比對行為。 |
(D\w+) |
比對一個大寫的「D」後面接著一或多個字元。 這是第一個捕捉群組。 |
\s |
比對空白字符。 |
(?ixn) |
從現在開始,比較不區分大小寫、只進行明確擷取,並忽略正則表達式中的空白。 |
(?#case-insensitive comparison) |
註解。 這不會影響模式比對行為。 |
(d\w+) |
比對大寫或小寫「d」後面接著一或多個單詞字符。 這是第二個擷取群組。 |
\b |
比對字邊界。 |
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comparison)d\w+)\b";
Regex rgx = new Regex(pattern);
string input = "double dare double Double a Drooling dog The Dreaded Deep";
Console.WriteLine("Pattern: " + pattern.ToString());
// Match pattern using default options.
foreach (Match match in rgx.Matches(input))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
{
for (int ctr = 1; ctr <match.Groups.Count; ctr++)
Console.WriteLine($" Group {ctr}: {match.Groups[ctr].Value}");
}
}
}
}
// The example displays the following output:
// Pattern: \b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comp
// arison)d\w+)\b
// Drooling dog
// Group 1: Drooling
// Dreaded Deep
// Group 1: Dreaded
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comparison)d\w+)\b"
Dim rgx As New Regex(pattern)
Dim input As String = "double dare double Double a Drooling dog The Dreaded Deep"
Console.WriteLine("Pattern: " + pattern.ToString())
' Match pattern using default options.
For Each match As Match In rgx.Matches(input)
Console.WriteLine(match.Value)
If match.Groups.Count > 1 Then
For ctr As Integer = 1 To match.Groups.Count - 1
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups(ctr).Value)
Next
End If
Next
End Sub
End Module
' The example displays the following output:
' Pattern: \b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comp
' arison)d\w+)\b
' Drooling dog
' Group 1: Drooling
' Dreaded Deep
' Group 1: Dreaded
行尾批注
數字元號 (#) 會標記 x 模式批註,該批註從正則表示式模式結尾的未逸出 # 字元開始,並繼續直到行尾為止。 若要使用此建構,您必須啟用 x 選項(透過內嵌選項),或在具現RegexOptions.IgnorePatternWhitespace化物件或呼叫靜態option方法時,將值Regex提供給 Regex 參數。
下列範例說明行尾批注建構。 它會判斷字串是否為包含至少一個格式項目的複合格式字串。 下表描述正規表示式模式中的建構:
\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.
| 樣式 | 說明 |
|---|---|
\{ |
比對開頭括弧。 |
\d+ |
比對一個或多個十進位數字。 |
(,-*\d+)* |
比對零或一個出現的逗號,後面接著選擇性減號,後面接著一或多個十進制數。 |
(\:\w{1,4}?)* |
比對零或一次出現的冒號,後面接著一到四個空格符,但盡可能減少。 |
\} |
匹配右括號 |
(?x) |
啟用忽略模式空格符選項,以便辨識行尾批注。 |
# Looks for a composite format item. |
行末註解。 |
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.";
string input = "{0,-3:F}";
Console.WriteLine($"'{input}':");
if (Regex.IsMatch(input, pattern))
Console.WriteLine(" contains a composite format item.");
else
Console.WriteLine(" does not contain a composite format item.");
}
}
// The example displays the following output:
// '{0,-3:F}':
// contains a composite format item.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."
Dim input As String = "{0,-3:F}"
Console.WriteLine("'{0}':", input)
If Regex.IsMatch(input, pattern) Then
Console.WriteLine(" contains a composite format item.")
Else
Console.WriteLine(" does not contain a composite format item.")
End If
End Sub
End Module
' The example displays the following output:
' '{0,-3:F}':
' contains a composite format item.
請注意,批注也可以藉由呼叫 (?x) 方法並傳遞Regex.IsMatch(String, String, RegexOptions)列舉值來辨識批註,而不是在正則表達式中提供 RegexOptions.IgnorePatternWhitespace 建構。