規則運算式中的其他建構Miscellaneous Constructs in Regular Expressions

.NET 中的規則運算式包含三個其他語言建構。Regular expressions in .NET include three miscellaneous language constructs. 其中一個可讓您在規則運算式模式的中間,啟用或停用特定比對選項。One lets you enable or disable particular matching options in the middle of a regular expression pattern. 其餘兩個可讓您在規則運算式中包含註解。The remaining two let you include comments in a regular expression.

內嵌選項Inline Options

您可以使用下列語法,設定或停用部分規則運算式的特定模式比對選項You can set or disable specific pattern matching options for part of a regular expression by using the syntax

(?imnsx-imnsx)

您在問號之後列出要啟用的選項,並在減號之後列出要停用的選項。You list the options you want to enable after the question mark, and the options you want to disable after the minus sign. 下表會說明每個選項。The following table describes each option. 如需每個選項的詳細資訊,請參閱規則運算式選項For more information about each option, see Regular Expression Options.

選項Option 描述Description
i 不區分大小寫的比對。Case-insensitive matching.
m 多行模式。Multiline mode.
n 僅明確擷取Explicit captures only. (括號不可作為擷取群組)。(Parentheses do not act as capturing groups.)
s 單行模式。Single-line mode.
x 忽略未逸出的空白字元,並允許 x 模式註解。Ignore unescaped white space, and allow x-mode comments.

(?imnsx-imnsx) 建構所定義之規則運算式選項中的任何變更,其效果會一直維持到封入群組的結尾。Any change in regular expression options defined by the (?imnsx-imnsx) construct remains in effect until the end of the enclosing group.

注意

(?imnsx-imnsx:subexpression) 群組建構會為子運算式提供完全相同的功能。The (?imnsx-imnsx:subexpression) grouping construct provides identical functionality for a subexpression. 如需詳細資訊,請參閱分組建構For more information, see Grouping Constructs.

下列範例會使用 inx 選項來啟用不區分大小寫和明確擷取,並忽略規則運算式中間規則運算式模式中的空白字元。The following example uses the i, n, and x options to enable case insensitivity and explicit captures, and to ignore white space in the regular expression pattern in the middle of a regular expression.

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 {0}: {1}", 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 {0}: '{1}'", 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'

此範例會定義兩個規則運算式。The example defines two regular expressions. 第一個規則運算式 \b(D\w+)\s(d\w+)\b 會比對開頭為大寫 "D" 和小寫 "d" 的兩個連續字組。The first, \b(D\w+)\s(d\w+)\b, matches two consecutive words that begin with an uppercase "D" and a lowercase "d". 第二個規則運算式 \b(D\w+)(?ixn) \s (d\w+) \b 會使用內嵌選項來修改此模式,如下表所述。The second regular expression, \b(D\w+)(?ixn) \s (d\w+) \b, uses inline options to modify this pattern, as described in the following table. 然後比較結果,以確認 (?ixn) 建構的效果。A comparison of the results confirms the effect of the (?ixn) construct.

模式Pattern 描述Description
\b 從字緣開始。Start at a word boundary.
(D\w+) 比對後面接著一個或多個文字字元的大寫 "D"。Match a capital "D" followed by one or more word characters. 這是第一個擷取群組。This is the first capture group.
(?ixn) 從這裡開始,進行不區分大小寫的比較、只進行明確擷取,並忽略規則運算式模式中的空白字元。From this point on, make comparisons case-insensitive, make only explicit captures, and ignore white space in the regular expression pattern.
\s 比對空白字元。Match a white-space character.
(d\w+) 比對後面接著一個或多個文字字元的大寫或小寫 "d"。Match an uppercase or lowercase "d" followed by one or more word characters. 因為已啟用 n (明確擷取) 選項,所以不會擷取此群組。This group is not captured because the n (explicit capture) option was enabled..
\b 比對字邊界。Match a word boundary.

內嵌註解Inline Comment

(?# comment) 建構可讓您在規則運算式中包含內嵌註解。The (?# comment) construct lets you include an inline comment in a regular expression. 規則運算式引擎不會在模式比對中使用註解的任一部分,不過,會將註解包含在 Regex.ToString 方法所傳回的字串中。The regular expression engine does not use any part of the comment in pattern matching, although the comment is included in the string that is returned by the Regex.ToString method. 註解會在第一個右括號結束。The comment ends at the first closing parenthesis.

下列範例會重複上一節範例中的第一個規則運算式模式。The following example repeats the first regular expression pattern from the example in the previous section. 它會將兩個內嵌註解加入規則運算式,以指出比較是否區分大小寫。It adds two inline comments to the regular expression to indicate whether the comparison is case-sensitive. 規則運算式模式 \b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comparison)d\w+)\b 定義如下。The regular expression pattern, \b((?# case-sensitive comparison)D\w+)\s(?ixn)((?#case-insensitive comparison)d\w+)\b, is defined as follows.

模式Pattern 描述Description
\b 從字緣開始。Start at a word boundary.
(?# case-sensitive comparison) 註解。A comment. 它不會影響模式比對行為。It does not affect pattern-matching behavior.
(D\w+) 比對後面接著一個或多個文字字元的大寫 "D"。Match a capital "D" followed by one or more word characters. 這是第一個擷取群組。This is the first capturing group.
\s 比對空白字元。Match a white-space character.
(?ixn) 從這裡開始,進行不區分大小寫的比較、只進行明確擷取,並忽略規則運算式模式中的空白字元。From this point on, make comparisons case-insensitive, make only explicit captures, and ignore white space in the regular expression pattern.
(?#case-insensitive comparison) 註解。A comment. 它不會影響模式比對行為。It does not affect pattern-matching behavior.
(d\w+) 比對後面接著一個或多個文字字元的大寫或小寫 "d"。Match an uppercase or lowercase "d" followed by one or more word characters. 這是第二個擷取群組。This is the second capture group.
\b 比對字邊界。Match a word boundary.
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 {0}: {1}", 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

行結尾註解End-of-Line Comment

數字符號 (#) 會標記 x 模式註解,從規則運算式模式結尾中未逸出的 # 字元開始,並持續到該行結尾。A number sign (#)marks an x-mode comment, which starts at the unescaped # character at the end of the regular expression pattern and continues until the end of the line. 若要使用此建構,您必須在將 Regex 物件具現化或呼叫靜態 Regex 方法時,啟用 x 選項 (透過內嵌選項),或將 RegexOptions.IgnorePatternWhitespace 值提供給 option 參數。To use this construct, you must either enable the x option (through inline options) or supply the RegexOptions.IgnorePatternWhitespace value to the option parameter when instantiating the Regex object or calling a static Regex method.

下列範例說明行結尾註解建構。The following example illustrates the end-of-line comment construct. 它會判斷字串是否為至少包含一個格式項目的複合格式字串。It determines whether a string is a composite format string that includes at least one format item. 下表說明規則運算式模式中的建構:The following table describes the constructs in the regular expression pattern:

\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.

模式Pattern 描述Description
\{ 比對左括號。Match an opening brace.
\d+ 比對一個或多個十進位數字。Match one or more decimal digits.
(,-*\d+)* 比對零個或一個出現的逗號,後面接著一個選擇性減號,再接著一個或多個十進位數字。Match zero or one occurrence of a comma, followed by an optional minus sign, followed by one or more decimal digits.
(\:\w{1,4}?)* 比對零個或一個出現的冒號,後面接著一到四個 (但越少越好) 空白字元。Match zero or one occurrence of a colon, followed by one to four, but as few as possible, white-space characters.
\} 比對右括號。Match a closing brace.
(?x) 啟用忽略模式空白字元選項,以辨識行結尾註解。Enable the ignore pattern white-space option so that the end-of-line comment will be recognized.
# Looks for a composite format item. 行結尾註解。An end-of-line comment.
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("'{0}':", 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 列舉值傳遞給此方法,來辨識註解。Note that, instead of providing the (?x) construct in the regular expression, the comment could also have been recognized by calling the Regex.IsMatch(String, String, RegexOptions) method and passing it the RegexOptions.IgnorePatternWhitespace enumeration value.

請參閱See also