相关文章推荐

一个字符类定义一组字符,其中的任一字符均可出现在输入字符串中以便成功匹配。 .NET 中的正则表达式语言支持以下字符类:

  • 正字符组。 输入字符串中的字符必须匹配一组指定的字符中的某个字符。 有关详细信息,请参阅 正字符组 。

  • 负字符组。 输入字符串中的字符不得匹配一组指定的字符中的某个字符。 有关详细信息,请参阅 负字符组 。

  • 任意字符。 正则表达式中的 . (圆点或句点)字符是匹配除 \n 之外的任何字符的通配符字符。 有关详细信息,请参阅 任意字符 。

  • 通用 Unicode 类别或命名块。 输入字符串中的字符必须为特定 Unicode 类别的成员,或必须位于一系列连续的 Unicode 字符中才能成功匹配。 有关详细信息,请参阅 Unicode 类别或 Unicode 块 。

  • 负通用 Unicode 类别或命名块。 输入字符串中的字符不得为特定 Unicode 类别的成员,也不得位于一系列连续的 Unicode 字符中以便成功匹配。 有关详细信息,请参阅 负 Unicode 类别或 Unicode 块 。

  • 单词字符。 输入字符串中的字符可以属于适合单词中字符的任何 Unicode 类别。 有关详细信息,请参阅 单词字符 。

  • 非单词字符。 输入字符串中的字符可以属于作为非单词字符的任何 Unicode 类别。 有关详细信息,请参阅 非单词字符 。

  • 空白字符。 输入字符串中的字符可以是任何 Unicode 分隔符字符以及众多控制字符中的任一字符。 有关详细信息,请参阅 空白字符 。

  • 非空白字符。 输入字符串中的字符可以是作为非空白字符的任何字符。 有关详细信息,请参阅 非空白字符 。

  • 十进制数字。 输入字符串中的字符可以是归类为 Unicode 十进制数字的众多字符中的任一字符。 有关详细信息,请参阅 十进制数字字符 。

  • 非十进制数字。 输入字符串中的字符可以是任何非 Unicode 十进制数字。 有关详细信息,请参阅 十进制数字字符 。

    .NET 支持字符类减法表达式,通过该表达式可以定义一组字符作为从一个字符类中排除另一字符类的结果。 有关详细信息,请参阅 字符类减法 。

    按类别匹配字符的字符类(如用于匹配字词字符的 \w ,或用于匹配 Unicode 类别的 \p{} )依赖 CharUnicodeInfo 类提供字符类别信息。 在 .NET Framework 4.6.2 及更高版本中,字符类别基于 Unicode 标准 8.0.0 版 。

    正字符组:[ ]

    正字符组指定一个字符列表,其中的任何一个字符可出现在输入字符串中以便进行匹配。 此字符列表可以单独指定和/或作为范围指定。

    用于指定各个字符列表的语法如下所示:

    [*character_group*]

    其中, character_group 是单个字符的列表,这些字符可出现在输入字符串中以便成功匹配。 character _group 可以包含一个或多个文本字符、 转义字符 或字符类的任意组合。

    用于指定字符范围的语法如下:

    [firstCharacter-lastCharacter]

    其中, firstCharacter 是范围的开始字符, lastCharacter 是范围的结束字符。 字符范围是通过以下方式定义的一系列连续字符:指定系列中的第一个字符,连字符 (-),然后指定系列中的最后一个字符。 如果两个字符具有相邻的 Unicode 码位,则这两个字符是连续的。 firstCharacter 必须是码位较低的字符,而 lastCharacter 必须是码位较高的字符 。

    由于正字符组可以包含一组字符和一个字符范围,因此连字符 ( - ) 始终被解释为范围分隔符,除非它是该组的第一个或最后一个字符。

    下表列出了一些常见的包含正字符类的正则表达式模式。

    下面的示例定义包含字符“a”和“e”的正字符组,以使输入字符串必须包含单词“grey”或“gray”且后跟另一个单词以便进行匹配。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          string pattern = @"gr[ae]y\s\S+?[\s\p{P}]";
          string input = "The gray wolf jumped over the grey wall.";
          MatchCollection matches = Regex.Matches(input, pattern);
          foreach (Match match in matches)
             Console.WriteLine($"'{match.Value}'");
    // The example displays the following output:
    //       'gray wolf '
    //       'grey wall.'
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "gr[ae]y\s\S+?[\s\p{P}]"
            Dim input As String = "The gray wolf jumped over the grey wall."
            Dim matches As MatchCollection = Regex.Matches(input, pattern)
            For Each match As Match In matches
                Console.WriteLine($"'{match.Value}'")
        End Sub
    End Module
    ' The example displays the following output:
    '       'gray wolf '
    '       'grey wall.'
    

    按以下方式定义正则表达式 gr[ae]y\s\S+?[\s|\p{P}]:

    下面的示例匹配以任何大写字母开头的单词。 它使用子表达式 [A-Z] 表示从 A 到 Z 的大写字母范围。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          string pattern = @"\b[A-Z]\w*\b";
          string input = "A city Albany Zulu maritime Marseilles";
          foreach (Match match in Regex.Matches(input, pattern))
             Console.WriteLine(match.Value);
    // The example displays the following output:
    //       A
    //       Albany
    //       Zulu
    //       Marseilles
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "\b[A-Z]\w*\b"
            Dim input As String = "A city Albany Zulu maritime Marseilles"
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(match.Value)
        End Sub
    End Module
    

    正则表达式 \b[A-Z]\w*\b 的定义如下表所示。

    负字符组指定一个字符列表,这些字符不得出现在输入字符串中以便进行匹配。 此字符列表可以单独指定和/或作为范围指定。

    用于指定各个字符列表的语法如下所示:

    [*^character_group*]

    其中,character_group 是单个字符的列表,这些字符不可出现在输入字符串中以便成功匹配。 character_group 可以包含一个或多个文本字符、转义字符或字符类的任意组合。

    用于指定字符范围的语法如下:

    [^*firstCharacter*-*lastCharacter*]

    其中,firstCharacter 是范围的开始字符,lastCharacter 是范围的结束字符。 字符范围是通过以下方式定义的一系列连续字符:指定系列中的第一个字符,连字符 (-),然后指定系列中的最后一个字符。 如果两个字符具有相邻的 Unicode 码位,则这两个字符是连续的。 firstCharacter 必须是码位较低的字符,而 lastCharacter 必须是码位较高的字符。

    由于负字符组可以包含一组字符和一个字符范围,因此连字符 (-) 始终被解释为范围分隔符,除非它是该组的第一个或最后一个字符。

    可以连接两个或更多字符范围。 例如,若要指定从“0”至“9”的十进制数范围、从“a”至“f”的小写字母范围,以及从“A”至“F”的大写字母范围,请使用 [0-9a-fA-F]。

    负字符组中的前导符 (^) 是强制的,指示字符组为负字符组,而不是正字符组。

    较大正则表达式模式中的负字符组不是零宽度断言。 也就是说,在评估负字符组后,正则表达式引擎会在输入字符串中提升一个字符。

    下表列出了一些常见的包含负字符组的正则表达式模式。

    string pattern = @"\bth[^o]\w+\b"; string input = "thought thing though them through thus thorough this"; foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Value); // The example displays the following output: // thing // them // through // thus // this
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "\bth[^o]\w+\b"
            Dim input As String = "thought thing though them through thus " + _
                                  "thorough this"
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(match.Value)
        End Sub
    End Module
    ' The example displays the following output:
    '       thing
    '       them
    '       through
    '       thus
    '       this
    

    正则表达式 \bth[^o]\w+\b 的定义如下表所示。

    句点字符 (.) 匹配除 \n(换行符 \u000A)之外的任何字符,有以下两个限制:

  • 如果通过 RegexOptions.Singleline 选项修改正则表达式模式,或者通过 . 选项修改包含 s 字符类的模式的部分,则 . 可匹配任何字符。 有关详细信息,请参阅 正则表达式选项。

    下面的示例阐释了默认情况下以及使用 . 选项的情况下 RegexOptions.Singleline 字符类的不同的行为。 正则表达式 ^.+ 在字符串开头开始并匹配每个字符。 默认情况下,匹配在第一行的结尾结束;正则表达式模式匹配回车符、\r 或 \u000D,但不匹配 \n。 由于 RegexOptions.Singleline 选项将整个输入字符串解释为单行,因此它匹配输入字符串中的每个字符,包括 \n。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          string pattern = "^.+";
          string input = "This is one line and" + Environment.NewLine + "this is the second.";
          foreach (Match match in Regex.Matches(input, pattern))
             Console.WriteLine(Regex.Escape(match.Value));
          Console.WriteLine();
          foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Singleline))
             Console.WriteLine(Regex.Escape(match.Value));
    // The example displays the following output:
    //       This\ is\ one\ line\ and\r
    //       This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "^.+"
            Dim input As String = "This is one line and" + vbCrLf + "this is the second."
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(Regex.Escape(match.Value))
            Console.WriteLine()
            For Each match As Match In Regex.Matches(input, pattern, RegexOptions.SingleLine)
                Console.WriteLine(Regex.Escape(match.Value))
        End Sub
    End Module
    ' The example displays the following output:
    '       This\ is\ one\ line\ and\r
    '       This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
    

    由于它匹配除 \n 之外的任何字符,因此 . 字符类也匹配 \r(回车符 \u000D)。

  • 正字符组或负字符组中的句点字符将被视为原义句点字符,而非字符类。 有关详细信息,请参阅本主题前面部分的正字符组和负字符组。 下面的示例通过定义包括句点字符 (.) 的正则表达式作为字符类和正字符组的成员来进行这方面的演示。 正则表达式 \b.*[.?!;:](\s|\z) 在字边界处开始,匹配任何字符直到遇到五个标点符号标记之一(包括句点),然后匹配空白字符或字符串的末尾。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          string pattern = @"\b.*[.?!;:](\s|\z)";
          string input = "this. what: is? go, thing.";
          foreach (Match match in Regex.Matches(input, pattern))
             Console.WriteLine(match.Value);
    // The example displays the following output:
    //       this. what: is? go, thing.
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As STring = "\b.*[.?!;:](\s|\z)"
            Dim input As String = "this. what: is? go, thing."
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(match.Value)
        End Sub
    End Module
    ' The example displays the following output:
    '       this. what: is? go, thing.
    

    由于它匹配任何字符,因此当正则表达式模式尝试多次匹配任何字符时,. 语言元素通常会与惰性限定符一起使用。 有关更多信息,请参见 数量词。

    Unicode 类别或 Unicode 块:\p{}

    Unicode 标准为每个常规类别分配一个字符。 例如,特定字符可以是大写字母(由 Lu 类别表示),十进制数字(Nd 类别)、数学符号(Sm 类别)或段落分隔符(Zl 类别)。 Unicode 标准中的特定字符集也占据连续码位的特定区域或块。 例如,可在 \u0000 和 \u007F 之间找到基本拉丁字符集,并可在 \u0600 和 \u06FF 之间找到阿拉伯语字符集。

    正则表达式构造

    name}\p{

    匹配属于 Unicode 常规类别或命名块的任何字符,其中,name 是类别缩写或命名块的名称。 有关类别缩写的列表,请参阅本主题稍后的支持的 Unicode 常规类别部分。 有关命名块的列表,请参阅本主题稍后的支持的命名块部分。

    如果首先通过调用 String.Normalize 方法规范化字符串,则可能会改进匹配。

    下面的示例使用 \p{名称} 构造以匹配 Unicode 常规类别(在该示例中为 Pd 或“标点,短划线”类别)和命名块(IsGreek 和 IsBasicLatin 命名块)。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          string pattern = @"\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+";
          string input = "Κατα Μαθθαίον - The Gospel of Matthew";
          Console.WriteLine(Regex.IsMatch(input, pattern));        // Displays True.
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"
            Dim input As String = "Κατα Μαθθαίον - The Gospel of Matthew"
            Console.WriteLine(Regex.IsMatch(input, pattern))         ' Displays True.
        End Sub
    End Module
    

    正则表达式 \b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+ 的定义如下表所示。

    负 Unicode 类别或 Unicode 块:\P{}

    Unicode 标准为每个常规类别分配一个字符。 例如,特定字符可以是大写字母(由 Lu 类别表示),十进制数字(Nd 类别)、数学符号(Sm 类别)或段落分隔符(Zl 类别)。 Unicode 标准中的特定字符集也占据连续码位的特定区域或块。 例如,可在 \u0000 和 \u007F 之间找到基本拉丁字符集,并可在 \u0600 和 \u06FF 之间找到阿拉伯语字符集。

    正则表达式构造

    name}\P{

    匹配不属于 Unicode 常规类别或命名块的任何字符,其中,name是类别缩写或命名块的名称。 有关类别缩写的列表,请参阅本主题稍后的支持的 Unicode 常规类别部分。 有关命名块的列表,请参阅本主题稍后的支持的命名块部分。

    如果首先通过调用 String.Normalize 方法规范化字符串,则可能会改进匹配。

    下面的示例使用 \P{name}构造来删除数字字符串中的任何货币符号(在该示例中为 Sc 或“符号,货币”类别)。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          string pattern = @"(\P{Sc})+";
          string[] values = { "$164,091.78", "£1,073,142.68", "73¢", "€120" };
          foreach (string value in values)
             Console.WriteLine(Regex.Match(value, pattern).Value);
    // The example displays the following output:
    //       164,091.78
    //       1,073,142.68
    //       73
    //       120
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "(\P{Sc})+"
            Dim values() As String = {"$164,091.78", "£1,073,142.68", "73¢", "€120"}
            For Each value As String In values
                Console.WriteLine(Regex.Match(value, pattern).Value)
        End Sub
    End Module
    ' The example displays the following output:
    '       164,091.78
    '       1,073,142.68
    '       73
    '       120
    

    正则表达式模式 (\P{Sc})+ 匹配不为货币符号的一个或多个字符;它有效地从结果字符串中抽出任何货币符号。

    单词字符:\w

    \w 与任何单词字符匹配。 单词字符是下表中列出的任何 Unicode 类别的成员。

    Category

    如果指定了符合 ECMAScript 的行为,则 \w 等效于 [a-zA-Z_0-9]。 有关 ECMAScript 正则表达式的信息,请参阅正则表达式选项中的“ECMAScript 匹配行为”部分。

    由于它匹配任何单词字符,因此当正则表达式模式尝试多次匹配任何单词字符且后跟特定单词字符时,\w 语言元素通常会与惰性限定符一起使用。 有关更多信息,请参见 数量词。

    下面的示例使用 \w 语言元素来匹配单词中的重复字符。 该示例定义可按如下方式解释的正则表达式模式 (\w)\1。

    string pattern = @"(\w)\1"; string[] words = { "trellis", "seer", "latter", "summer", "hoarse", "lesser", "aardvark", "stunned" }; foreach (string word in words) Match match = Regex.Match(word, pattern); if (match.Success) Console.WriteLine("'{0}' found in '{1}' at position {2}.", match.Value, word, match.Index); Console.WriteLine("No double characters in '{0}'.", word); // The example displays the following output: // 'll' found in 'trellis' at position 3. // 'ee' found in 'seer' at position 1. // 'tt' found in 'latter' at position 2. // 'mm' found in 'summer' at position 2. // No double characters in 'hoarse'. // 'ss' found in 'lesser' at position 2. // 'aa' found in 'aardvark' at position 0. // 'nn' found in 'stunned' at position 3.
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "(\w)\1"
            Dim words() As String = {"trellis", "seer", "latter", "summer", _
                                      "hoarse", "lesser", "aardvark", "stunned"}
            For Each word As String In words
                Dim match As Match = Regex.Match(word, pattern)
                If match.Success Then
                    Console.WriteLine("'{0}' found in '{1}' at position {2}.", _
                                      match.Value, word, match.Index)
                    Console.WriteLine("No double characters in '{0}'.", word)
                End If
        End Sub
    End Module
    ' The example displays the following output:
    '       'll' found in 'trellis' at position 3.
    '       'ee' found in 'seer' at position 1.
    '       'tt' found in 'latter' at position 2.
    '       'mm' found in 'summer' at position 2.
    '       No double characters in 'hoarse'.
    '       'ss' found in 'lesser' at position 2.
    '       'aa' found in 'aardvark' at position 0.
    '       'nn' found in 'stunned' at position 3.
    

    非单词字符:\W

    \W 匹配任何非单词字符。 \W 语言元素等效于以下字符类:

    [^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}]

    换言之,它与下表列出的 Unicode 类别中的字符以外的任何字符匹配。

    Category

    如果指定了符合 ECMAScript 的行为,则 \W 等效于 [^a-zA-Z_0-9]。 有关 ECMAScript 正则表达式的信息,请参阅正则表达式选项中的“ECMAScript 匹配行为”部分。

    由于它匹配任何非单词字符,因此当正则表达式模式尝试多次匹配任何非单词字符且后跟特定非单词字符时,\W 语言元素通常会与惰性限定符一起使用。 有关更多信息,请参见 数量词。

    下面的示例阐释 \W 字符类。 它定义正则表达式模式 \b(\w+)(\W){1,2},该模式匹配后跟一个或两个非单词字符(例如,空白或标点符号)的单词。 正则表达式模式可以解释为下表中所示内容。

    string pattern = @"\b(\w+)(\W){1,2}"; string input = "The old, grey mare slowly walked across the narrow, green pasture."; foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Value); Console.Write(" Non-word character(s):"); CaptureCollection captures = match.Groups[2].Captures; for (int ctr = 0; ctr < captures.Count; ctr++) Console.Write(@"'{0}' (\u{1}){2}", captures[ctr].Value, Convert.ToUInt16(captures[ctr].Value[0]).ToString("X4"), ctr < captures.Count - 1 ? ", " : ""); Console.WriteLine(); // The example displays the following output: // The // Non-word character(s):' ' (\u0020) // old, // Non-word character(s):',' (\u002C), ' ' (\u0020) // grey // Non-word character(s):' ' (\u0020) // mare // Non-word character(s):' ' (\u0020) // slowly // Non-word character(s):' ' (\u0020) // walked // Non-word character(s):' ' (\u0020) // across // Non-word character(s):' ' (\u0020) // the // Non-word character(s):' ' (\u0020) // narrow, // Non-word character(s):',' (\u002C), ' ' (\u0020) // green // Non-word character(s):' ' (\u0020) // pasture. // Non-word character(s):'.' (\u002E)
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "\b(\w+)(\W){1,2}"
            Dim input As String = "The old, grey mare slowly walked across the narrow, green pasture."
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(match.Value)
                Console.Write("   Non-word character(s):")
                Dim captures As CaptureCollection = match.Groups(2).Captures
                For ctr As Integer = 0 To captures.Count - 1
                    Console.Write("'{0}' (\u{1}){2}", captures(ctr).Value, _
                                  Convert.ToUInt16(captures(ctr).Value.Chars(0)).ToString("X4"), _
                                  If(ctr < captures.Count - 1, ", ", ""))
                Console.WriteLine()
        End Sub
    End Module
    ' The example displays the following output:
    '       The
    '          Non-word character(s):' ' (\u0020)
    '       old,
    '          Non-word character(s):',' (\u002C), ' ' (\u0020)
    '       grey
    '          Non-word character(s):' ' (\u0020)
    '       mare
    '          Non-word character(s):' ' (\u0020)
    '       slowly
    '          Non-word character(s):' ' (\u0020)
    '       walked
    '          Non-word character(s):' ' (\u0020)
    '       across
    '          Non-word character(s):' ' (\u0020)
    '       the
    '          Non-word character(s):' ' (\u0020)
    '       narrow,
    '          Non-word character(s):',' (\u002C), ' ' (\u0020)
    '       green
    '          Non-word character(s):' ' (\u0020)
    '       pasture.
    '          Non-word character(s):'.' (\u002E)
    

    由于第二个捕获组的 Group 对象仅包含单个捕获的非单词字符,因此该示例将从 CaptureCollection 属性返回的 Group.Captures 对象中检索所有捕获的非单词字符。

    空格字符:\s

    \s 匹配任意空格字符。 它等效于下表中列出的转义序列和 Unicode 类别。

    Category

    如果指定了符合 ECMAScript 的行为,则 \s 等效于 [ \f\n\r\t\v]。 有关 ECMAScript 正则表达式的信息,请参阅正则表达式选项中的“ECMAScript 匹配行为”部分。

    下面的示例阐释 \s 字符类。 它定义正则表达式模式 \b\w+(e)?s(\s|$),该模式匹配以“s”或“es”结尾且后跟一个空白字符或输入字符串末尾的单词。 正则表达式模式可以解释为下表中所示内容。

    string pattern = @"\b\w+(e)?s(\s|$)"; string input = "matches stores stops leave leaves"; foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Value); // The example displays the following output: // matches // stores // stops // leaves
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "\b\w+(e)?s(\s|$)"
            Dim input As String = "matches stores stops leave leaves"
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(match.Value)
        End Sub
    End Module
    ' The example displays the following output:
    '       matches
    '       stores
    '       stops
    '       leaves
    

    非空格字符:\S

    \S 匹配任何非空白字符。 它等效于 [^\f\n\r\t\v\x85\p{Z}] 正则表达式模式或与等效于 \s 的正则表达式模式(与空白字符匹配)相反。 有关详细信息,请参阅空白字符:\s。

    如果指定了符合 ECMAScript 的行为,则 \S 等效于 [^ \f\n\r\t\v]。 有关 ECMAScript 正则表达式的信息,请参阅正则表达式选项中的“ECMAScript 匹配行为”部分。

    下面的示例阐释 \S 语言元素。 正则表达式模式 \b(\S+)\s? 匹配由空白字符分隔的字符串。 匹配项的 GroupCollection 对象中的第二个元素包含匹配的字符串。 正则表达式可按下表中的方式解释。

    string pattern = @"\b(\S+)\s?"; string input = "This is the first sentence of the first paragraph. " + "This is the second sentence.\n" + "This is the only sentence of the second paragraph."; foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Groups[1]); // The example displays the following output: // This // is // the // first // sentence // of // the // first // paragraph. // This // is // the // second // sentence. // This // is // the // only // sentence // of // the // second // paragraph.
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "\b(\S+)\s?"
            Dim input As String = "This is the first sentence of the first paragraph. " + _
                                  "This is the second sentence." + vbCrLf + _
                                  "This is the only sentence of the second paragraph."
            For Each match As Match In Regex.Matches(input, pattern)
                Console.WriteLine(match.Groups(1))
        End Sub
    End Module
    ' The example displays the following output:
    '    This
    '    is
    '    the
    '    first
    '    sentence
    '    of
    '    the
    '    first
    '    paragraph.
    '    This
    '    is
    '    the
    '    second
    '    sentence.
    '    This
    '    is
    '    the
    '    only
    '    sentence
    '    of
    '    the
    '    second
    '    paragraph.
    

    十进制数字字符:\d

    \d 匹配任何十进制数字。 它等效于 \p{Nd} 正则表达式模式,该模式包含标准的十进制数字 0-9 以及众多其他字符集的十进制数字。

    如果指定了符合 ECMAScript 的行为,则 \d 等效于 [0-9]。 有关 ECMAScript 正则表达式的信息,请参阅正则表达式选项中的“ECMAScript 匹配行为”部分。

    下面的示例阐释 \d 语言元素。 它测试输入字符串是否表示美国和加拿大的有效电话号码。 正则表达式模式 ^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$ 的定义如下表所示。

    string pattern = @"^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"; string[] inputs = { "111 111-1111", "222-2222", "222 333-444", "(212) 111-1111", "111-AB1-1111", "212-111-1111", "01 999-9999" }; foreach (string input in inputs) if (Regex.IsMatch(input, pattern)) Console.WriteLine(input + ": matched"); Console.WriteLine(input + ": match failed"); // The example displays the following output: // 111 111-1111: matched // 222-2222: matched // 222 333-444: match failed // (212) 111-1111: matched // 111-AB1-1111: match failed // 212-111-1111: matched // 01 999-9999: match failed
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"
            Dim inputs() As String = {"111 111-1111", "222-2222", "222 333-444", _
                                       "(212) 111-1111", "111-AB1-1111", _
                                       "212-111-1111", "01 999-9999"}
            For Each input As String In inputs
                If Regex.IsMatch(input, pattern) Then
                    Console.WriteLine(input + ": matched")
                    Console.WriteLine(input + ": match failed")
                End If
        End Sub
    End Module
    ' The example displays the following output:
    '       111 111-1111: matched
    '       222-2222: matched
    '       222 333-444: match failed
    '       (212) 111-1111: matched
    '       111-AB1-1111: match failed
    '       212-111-1111: matched
    '       01 999-9999: match failed
    

    非数字字符:\D

    \D 匹配任何非数字字符。 它等效于 \P{Nd} 正则表达式模式。

    如果指定了符合 ECMAScript 的行为,则 \D 等效于 [^0-9]。 有关 ECMAScript 正则表达式的信息,请参阅正则表达式选项中的“ECMAScript 匹配行为”部分。

    下面的示例阐释了 \D 语言元素。 它测试部件号等字符串是否包含适当的十进制和非十进制数字字符的组合。 正则表达式模式 ^\D\d{1,5}\D*$ 的定义如下表所示。

    string pattern = @"^\D\d{1,5}\D*$"; string[] inputs = { "A1039C", "AA0001", "C18A", "Y938518" }; foreach (string input in inputs) if (Regex.IsMatch(input, pattern)) Console.WriteLine(input + ": matched"); Console.WriteLine(input + ": match failed"); // The example displays the following output: // A1039C: matched // AA0001: match failed // C18A: matched // Y938518: match failed
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim pattern As String = "^\D\d{1,5}\D*$"
            Dim inputs() As String = {"A1039C", "AA0001", "C18A", "Y938518"}
            For Each input As String In inputs
                If Regex.IsMatch(input, pattern) Then
                    Console.WriteLine(input + ": matched")
                    Console.WriteLine(input + ": match failed")
                End If
        End Sub
    End Module
    ' The example displays the following output:
    

    支持的 Unicode 常规类别

    Unicode 定义下表列出的常规类别。 有关详细信息,请参阅 Unicode 字符数据库(5.7.1 部分的表 12)中的“UCD 文件格式”和“常规类别值”子主题。

    可以通过将任何特定字符传递到 GetUnicodeCategory 方法来确定该字符的 Unicode 类别。 下面的示例使用 GetUnicodeCategory 方法来确定包含所选拉丁字符的数组中的每个元素的类别。

    using System;
    using System.Text.RegularExpressions;
    public class Example
       public static void Main()
          char[] chars = { 'a', 'X', '8', ',', ' ', '\u0009', '!' };
          foreach (char ch in chars)
             Console.WriteLine("'{0}': {1}", Regex.Escape(ch.ToString()),
                               Char.GetUnicodeCategory(ch));
    // The example displays the following output:
    //       'a': LowercaseLetter
    //       'X': UppercaseLetter
    //       '8': DecimalDigitNumber
    //       ',': OtherPunctuation
    //       '\ ': SpaceSeparator
    //       '\t': Control
    //       '!': OtherPunctuation
    
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim chars() As Char = {"a"c, "X"c, "8"c, ","c, " "c, ChrW(9), "!"c}
            For Each ch As Char In chars
                Console.WriteLine("'{0}': {1}", Regex.Escape(ch.ToString()), _
                                  Char.GetUnicodeCategory(ch))
        End Sub
    End Module
    ' The example displays the following output:
    '       'a': LowercaseLetter
    '       'X': UppercaseLetter
    '       '8': DecimalDigitNumber
    '       ',': OtherPunctuation
    '       '\ ': SpaceSeparator
    '       '\t': Control
    '       '!': OtherPunctuation
    

    支持的命名块

    .NET 提供下表中所列的命名块。 该组支持的命名块基于 Unicode 4.0 和 Perl 5.6。 有关使用命名块的正则表达式,请参阅 Unicode 类别或 Unicode 块:\p{} 部分。

    字符类减法:[base_group - [excluded_group]]

    一个字符类定义一组字符。 字符类减法将产生一组字符,该组字符是从一个字符类中排除另一个字符类中的字符的结果。

    字符类减法表达式具有以下形式:

    [base_group-[excluded_group]]

    方括号 ([]) 和连字符 (-) 是强制的。 base_group 是正字符组或负字符组。 excluded_group 部分是另一个正字符组或负字符组,或者是另一个字符类减法表达式(即,可以嵌套字符类减法表达式)。

    例如,假设你有一个由从“a”至“z”范围内的字符组成的基本组。 若要定义由除字符“m”之外的基本组组成的字符集,请使用 [a-z-[m]]。 若要定义由除字符集“d”、“j”和“p”之外的基本组组成的字符集,请使用 [a-z-[djp]]。 若要定义由除从“m”至“p”字符范围之外的基本组组成的字符集,请使用 [a-z-[m-p]]。

    可考虑使用嵌套字符类减法表达式 [a-z-[d-w-[m-o]]]。 该表达式由最里面的字符范围向外计算。 首先,在从“d”至“w”的字符范围中减去从“m”至“o”的字符范围,这将产生从“d”至“l”和从“p”至“w”的字符集。 然后,在从“a”至“z”的字符范围中减去该集合,这将产生字符集 [abcmnoxyz]。

    可以将任何字符类用于字符类减法。 若要定义字符集,且该字符集包括除空白字符 (\s)、标点通用类别中的字符 (\p{P})、IsGreek 命名块中的字符 (\p{IsGreek}) 以及 Unicode NEXT LINE 控制字符 (\x85) 之外的所有从 \u0000 至 \uFFFF 的 Unicode 字符,请使用 [\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]。

    为字符类减法表达式选择将会产生有用结果的字符类。 避免使用产生空字符集的表达式,这将无法匹配任何内容,同时避免使用等效于初始基本组的表达式。 例如,表达式 [\p{IsBasicLatin}-[\x00-\x7F]] 从 IsBasicLatin 常规类别中减去 IsBasicLatin 字符范围内的所有字符,其结果为空集合。 类似地,表达式 [a-z-[0-9]] 的结果为初始基本组。 这是因为,基本组(它是从“a”至“z”的字母组成的字符范围)不包含排除组(它是从“0”至“9”的十进制数组成的字符范围)中的任何字符。

    下面的示例定义正则表达式 ^[0-9-[2468]]+$,该表达式匹配输入字符串中的零和奇数。 正则表达式模式可以解释为下表中所示内容。

    public static void Main() string[] inputs = { "123", "13579753", "3557798", "335599901" }; string pattern = @"^[0-9-[2468]]+$"; foreach (string input in inputs) Match match = Regex.Match(input, pattern); if (match.Success) Console.WriteLine(match.Value); // The example displays the following output: // 13579753 // 335599901
    Imports System.Text.RegularExpressions
    Module Example
        Public Sub Main()
            Dim inputs() As String = {"123", "13579753", "3557798", "335599901"}
            Dim pattern As String = "^[0-9-[2468]]+$"
            For Each input As String In inputs
                Dim match As Match = Regex.Match(input, pattern)
                If match.Success Then Console.WriteLine(match.Value)
        End Sub
    End Module
    ' The example displays the following output:
    '       13579753
    '       335599901
    
  • GetUnicodeCategory
  • 正则表达式语言 - 快速参考
  • 正则表达式选项
  •  
    推荐文章