zoukankan      html  css  js  c++  java
  • C#中的 正则表达式

      String 类包括许多字符串搜索和替换方法,当你要在较大字符串中定位文本字符串时,可以使用这些方法。 当你希望在较大字符串中定位若干子字符串之一时,或者当你希望在字符串中标识模式时,正则表达式最有用,,以下主要介绍下C#正则表达式的用法:

      字符转义

      正则表达式中的反斜杠字符 () 指示其后跟的字符是特殊字符(如下表所示),或应按原义解释该字符。

    转义字符

    描述

    模式

    匹配

    a

    与报警 (bell) 符 u0007 匹配。

    a

    “Error!”+“u0007”中的“u0007”

    

    在字符类中,与退格键 u0008 匹配。

    []{3,}

    “”中的“”

    与制表符 u0009 匹配。

    (w+)

    “item1 item2 ”中的“item1 ”和“item2 ”

    与回车符 u000D 匹配。 (  与换行符   不是等效的。)

    (w+)

    “ These are two lines.”中的“ These”

    v

    与垂直制表符 u000B 匹配。

    [v]{2,}

    “vvv”中的“vvv”

    f

    与换页符 u000C 匹配。

    [f]{2,}

    “fff”中的“fff”

    与换行符 u000A 匹配。

    (w+)

    “ These are two lines.”中的“ These”

    e

    与转义符 u001B 匹配。

    e

    “x001B”中的“x001B”

    nnn

    使用八进制表示形式指定字符(nnn 由二位或三位数字组成)。

    w40w

    “a bc d”中的

    “a b”和“c d”

    xnn

    使用十六进制表示形式指定字符(nn 恰好由两位数字组成)。

    wx20w

    “a bc d”中的

    “a b”和“c d”

    cX

    cx

    匹配 X 或 x 指定的 ASCII 控件字符,其中 X 或 x 是控件字符的字母。

    cC

    “x0003”中的“x0003”(Ctrl-C)

    unnnn

    使用十六进制表示形式匹配 Unicode 字符(由 nnnn 正确表示的四位数)。

    wu0020w

    “a bc d”中的

    “a b”和“c d”

    在后面带有不识别为本主题的此表和其他表中的转义符的字符时,与该字符匹配。 例如,* 与 x2A 相同,而 . 与 x2E 相同。 这允许正则表达式引擎区分语言元素(如 * 或 ?) 和字符文本(用 * 或 ?表示)。

    d+[+-x*]d+

    “(2+2) * 3*9”中的“2+2”和“3*9”

     

      字符类与一组字符中的任何一个字符匹配。 字符类包括下表中列出的语言元素。

    字符类

    描述

    模式

    匹配

    [character_group]

    匹配 character_group 中的任何单个字符。 默认情况下,匹配区分大小写。

    [ae]

    “gray”中的“a”

    “lane”中的“a”和“e”

    [^character_group]

    求反:与不在 character_group 中的任何单个字符匹配。 默认情况下,character_group 中的字符区分大小写。

    [^aei]

    “reign”中的“r”、“g”和“n”

    [第一个-last]

    字符范围:与从第一个最后一个的范围中的任何单个字符匹配。

    [A-Z]

    “AB123”中的“A”和“B”

    .

    通配符:与除 之外的任何单个字符匹配。

    若要匹配文本句点字符(. 或 u002E),你必须在该字符前面加上转义符 (.)。

    a.e

    “nave”中的“ave”

    “water”中的“ate”

    p{name}

    与 name 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。

    p{Lu}

    p{IsCyrillic}

    “City Lights”中的“C”和“L”

    “ДЖem”中的“Д”和“Ж”

    P{name}

    与不在 name 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。

    P{Lu}

    P{IsCyrillic}

    “City”中的“i”、“t”和“y”

    “ДЖem”中的“e”和“m”

    w

    与任何单词字符匹配。

    w

    “ID A1.3”中的“I”、“D”、“A”、“1”和“3”

    W

    与任何非单词字符匹配。

    W

    “ID A1.3”中的“ ”、“.”

    s

    与任何空白字符匹配。

    ws

    “ID A1.3”中的“D”

    S

    与任何非空白字符匹配。

    sS

    " _" in "int __ctr"

    d

    与任何十进制数字匹配。

    d

    “4 = IV”中的“4”

    D

    匹配不是十进制数的任意字符。

    D

    “4 = IV”中的“ ”、“=”、“ ”、“I”和“V”

     

      定位点或原子零宽度断言会使匹配成功或失败,具体取决于字符串中的当前位置,但它们不会使引擎在字符串中前进或使用字符。 下表中列出的元字符是定位点。

    断言

    描述

    模式

    匹配

    ^

    匹配必须从字符串或一行的开头开始。 

    ^d{3}

    “901”

    “901-”

    $

    匹配必须出现在字符串的末尾或出现在行或字符串末尾的   之前。

    -d{3}$

    “-333”

    “-333”

    A

    匹配必须出现在字符串的开头。

    Ad{3}

    “901”

    “901-”

    

    匹配必须出现在字符串的末尾或出现在字符串末尾的   之前。

    -d{3}

    “-333”

    “-333”

    z

    匹配必须出现在字符串的末尾。

    -d{3}z

    “-333”

    “-333”

    G

    匹配必须出现在上一个匹配结束的地方。

    G(d)

    “(1)(3)(5)[7](9)”中的“(1)”、“(3)”、“(5)”

    

    匹配必须出现在 w(字母数字)和 W(非字母数字)字符之间的边界上。

    w+sw+

    “them theme them them”中的“them theme”、“them them”

    B

    匹配不得出现在  边界上。

    Bendw*

    “end sends endure lender”中的“ends”和“ender”

     

      分组构造描述了正则表达式的子表达式,通常用于捕获输入字符串的子字符串。 分组构造包括下表中列出的语言元素。

    分组构造

    描述

    模式

    匹配

    (子表达式)

    捕获匹配的子表达式并将其分配到一个从 1 开始的序号中。

    (w)1

    “deep”中的“ee”

    (?< 名称> 子表达式)

    将匹配的子表达式捕获到一个命名组中。

    (?<double>w)k<double>

    “deep”中的“ee”

    (?< 名称 1 -名称 2 > 子表达式)

    定义平衡组定义。 有关详细信息,请参阅正则表达式中的分组构造中的“平衡组定义”部分。

    (((?'Open'()[^()]*)+((?'Close-Open'))[^()]*)+)*(?(Open)(?!))$

    “3+2^((1-3)*(3-1))”中的“((1-3)*(3-1))”

    (?: 子表达式)

    定义非捕获组。

    Write(?:Line)?

    “Console.WriteLine()”中的“WriteLine”

    “Console.Write(value)”中的“Write”

    (?imnsx-imnsx: 子表达式)

    应用或禁用子表达式中指定的选项。 有关详细信息,请参阅正则表达式选项

    Ad{2}(?i:w+)

    “A12xl A12XL a12xl”中的“A12xl”和“A12XL”

    (?= 子表达式)

    零宽度正预测先行断言。

    w+(?=.)

    “He is. The dog ran. The sun is out.”中的“is”、“ran”和“out”

    (?! 子表达式)

    零宽度负预测先行断言。

    (?!un)w+

    “unsure sure unity used”中的“sure”和“used”

    (?<= 子表达式)

    零宽度正回顾后发断言。

    (?<=19)d{2}

    “1851 1999 1950 1905 2003”中的“99”、“50”和“05”

    (?<! 子表达式)

    零宽度负回顾后发断言。

    (?<!19)d{2}

    “1851 1999 1950 1905 2003”中的“51”和“03”

    (?> 子表达式)

    非回溯(也称为“贪婪”)子表达式。

    [13579](?>A+B+)

    “1ABB 3ABBC 5AB 5AC”中的“1ABB”、“3ABB”和“5AB”

     

      限定符指定在输入字符串中必须存在上一个元素(可以是字符、组或字符类)的多少个实例才能出现匹配项。 限定符包括下表中列出的语言元素。

    限定符

    描述

    模式

    匹配

    *

    匹配上一个元素零次或多次。

    d*.d

    “.0”,“19.9”和“219.9”

    +

    匹配上一个元素一次或多次。

    "be+"

    “been”中的“bee”,“bent”中的“be”

    ?

    匹配上一个元素零次或一次。

    "rai?n"

    “ran”和“rain”

    {n}

    匹配上一个元素恰好 n 次。

    ",d{3}"

    “1,043.6”中的“,043”,“9,876,543,210”中的“,876”、“,543”和“,210”

    {n,}

    匹配上一个元素至少 n 次。

    "d{2,}"

    “166”,“29”和“1930”

    {n,m}

    匹配上一个元素至少 n 次,但不多于 m次。

    "d{3,5}"

    “166”、“17668”

    “193024”中的“19302”

    *?

    匹配上一个元素零次或多次,但次数尽可能少。

    d*?.d

    “.0”,“19.9”和“219.9”

    +?

    匹配上一个元素一次或多次,但次数尽可能少。

    "be+?"

    “been”中的“be”,“bent”中的“be”

    ??

    匹配上一个元素零次或一次,但次数尽可能少。

    "rai??n"

    “ran”和“rain”

    {n}?

    匹配前面的元素恰好 n 次。

    ",d{3}?"

    “1,043.6”中的“,043”,“9,876,543,210”中的“,876”、“,543”和“,210”

    {n,}?

    匹配上一个元素至少 n 次,但次数尽可能少。

    "d{2,}?"

    “166”,“29”和“1930”

    {n,m}?

    匹配上一个元素的次数介于 n 和 m 之间,但次数尽可能少。

    "d{3,5}?"

    “166”、“17668”

    “193024”中的“193”、“024”

     

      反向引用允许在同一正则表达式中随后标识以前匹配的子表达式。 下表列出了 .NET Framework 的正则表达式支持的反向引用构造。

    反向引用构造

    描述

    模式

    匹配

    数值

    后向引用。 匹配编号子表达式的值。

    (w)1

    “seek”中的“ee”

    k<name>

    命名后向引用。 匹配命名表达式的值。

    (?<char>w)k<char>

    “seek”中的“ee”

     

      替换构造用于修改正则表达式以启用 either/or 匹配。 这些构造包括下表中列出的语言元素。 

    替换构造

    描述

    模式

    匹配

    |

    匹配以竖线 (|) 字符分隔的任何一个元素。

    th(e|is|at)

    “this is the day.”中的“the”和“this” "

    (?(表达式)|no)

    如果正则表达式模式由 expression 匹配指定,则匹配 yes;否则,匹配可选 no 部分。 expression 被解释为零宽度断言。

    (?(A)Ad{2}|d{3})

    “A10 C103 910”中的“A10”和“910”

    (?(name)|no)

    如果 name(已命名或已编号的捕获组)具有匹配,则匹配 yes;否则,匹配可选 no

    (?<quoted>")?(?(quoted).+?"|S+s)

    “Dogs.jpg "Yiska playing.jpg"”中的 Dogs.jpg 和 "Yiska playing.jpg"

     

      替换是替换模式中支持的正则表达式语言元素。 

    字符

    描述

    模式

    替换模式

    输入字符串

    结果字符串

    $数值

    替换按组 number 匹配的子字符串。

    (w+)(s)(w+)

    $3$2$1

    "one two"

    "two one"

    ${name}

    替换按命名组 name 匹配的子字符串。

    (?<word1>w+)(s)(?<word2>w+)

    ${word2} ${word1}

    "one two"

    "two one"

    $$

    替换字符“$”。

    (d+)s?USD

    $$$1

    “103 USD”

    “$103”

    $&

    替换整个匹配项的一个副本。

    $?d*.?d+

    **$&**

    "$1.30"

    “**$1.30**”

    $`

    替换匹配前的输入字符串的所有文本。

    B+

    $`

    “AABBCC”

    “AAAACC”

    $'

    替换匹配后的输入字符串的所有文本。

    B+

    $'

    “AABBCC”

    “AACCCC”

    $+

    替换最后捕获的组。

    B+(C+)

    $+

    “AABBCCDD”

    AACCDD

    $_

    替换整个输入字符串。

    B+

    $_

    “AABBCC”

    “AAAABBCCCC”

     

    可以指定控制正则表达式引擎如何解释正则表达式模式的选项。 其中的许多选项可以指定为内联(在正则表达式模式中)或指定为一个或多个 RegexOptions 常量。 本快速参考仅列出内联选项。

    可通过两种方式指定内联选项:

    • 通过使用杂项构造(?imnsx-imnsx),可以用选项或选项组前的减号 (-) 关闭这些选项。 例如,(?i-mn) 启用不区分大小写的匹配 (i),关闭多行模式 (m) 并关闭未命名的组捕获 (n)。 该选项自定义选项的点开始应用于此正则表达式,且持续有效直到模式结束或者到另一构造反转此选项的点。

    • 通过使用分组构造(?imnsx-imnsx:子表达式)(只定义指定组的选项)。

    .NET Framework 正则表达式引擎支持以下内联选项。

    选项

    描述

    模式

    匹配

    i

    使用不区分大小写的匹配。

    (?i)a(?-i)aw+

    "aardvark", "aaaAuto" in "aardvark AAAuto aaaAuto Adam breakfast"

    m

    使用多行模式。 ^ 和 $ 匹配行的开头和结尾,但不匹配字符串的开头和结尾。

    有关示例,请参阅正则表达式选项中的“多行模式”部分。

     

    n

    不捕获未命名的组。

    有关示例,请参阅正则表达式选项中的“仅显式捕获”部分。

     

    s

    使用单行模式。

    有关示例,请参阅正则表达式选项中的“单行模式”部分。

     

    x

    忽略正则表达式模式中的非转义空白。

    (?x) d+ s w+ 

    “1 aardvark 2 cats IV centurions”中的“1 aardvark”、“2 cats”

     

      其他构造可修改某个正则表达式模式或提供有关该模式的信息。 下表列出了 .NET Framework 支持的其他构造。

    构造

    定义

    示例

    (?imnsx-imnsx)

    在模式中间对诸如不区分大小写这样的选项进行设置或禁用。 有关详细信息,请参阅正则表达式选项

    A(?i)bw+ 匹配“ABA Able Act”中的“ABA”和“Able”

    (?# 注释)

    内联注释。 该注释在第一个右括号处终止。

    A(?#Matches words starting with A)w+

    # [至行尾]

    X 模式注释。 该注释以非转义的 # 开头,并继续到行的结尾。

    (?x)Aw+#Matches words starting with A

    参考文档:

     msdn 正则表达式快速参考  https://msdn.microsoft.com/zh-cn/library/az24scfc(v=vs.110).aspx

                        http://www.cnblogs.com/ggjucheng/p/3423731.html

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;

    namespace CoreWebLibrary.Text.RegularExpressions
    {
        /**//// <summary>
        /// A utility class containing frequently used Regular Expression Patterns
        /// and two utility methods to see if a passed string conforms to the designated 
        /// pattern.
        /// </summary>
        public class Patterns
        {
         
          public const string EMAIL = @"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$" ;

          public const string US_ZIPCODE = @"^d{5}$" ;
          public const string US_ZIPCODE_PLUS_FOUR = @"^d{5}((-|s)?d{4})$";
          public const string US_ZIPCODE_PLUS_FOUR_OPTIONAL = @"^d{5}((-|s)?d{4})?$" ;

          /**//// <summary>
          /// Permissive US Telephone Regex. Does not allow extensions.
          /// </summary>
          /// <example>
          /// Allows: 324-234-3433, 3242343434, (234)234-234, (234) 234-2343
          /// </example>
          public const string US_TELEPHONE = @"^([(]{1}[0-9]{3}[)]{1}[.| |-]{0,1}|^[0-9]{3}[.|-| ]?)?[0-9]{3}(.|-| )?[0-9]{4}$";

          /**//// <summary>
          /// This matches a url in the generic format 
          /// scheme://authority/path?query#fragment
          /// </summary>
          /// <example>
          /// Allows: http://www.yahoo.com, https://www.yahoo.com, ftp://www.yahoo.com
          /// </example>
          public const string URL = @"^(?<Protocol>w+)://(?<Domain>[w.]+/?)S*$";

          /**//// <summary>
          /// This matches an ip address in the format xxx-xxx-xxx-xxx
          /// each group of xxx must be less than or equal to 255
          /// </summary>
          /// <example>
          /// Allows: 123.123.123.123, 192.168.1.1
          /// </example>
          public const string IP_ADDRESS = @"^(?<First>2[0-4]d|25[0-5]|[01]?dd?).(?<Second>2[0-4]d|25[0-5]|[01]?dd?).(?<Third>2[0-4]d|25[0-5]|[01]?dd?).(?<Fourth>2[0-4]d|25[0-5]|[01]?dd?)$";

          /**//// <summary>
          /// This matches a date in the format mm/dd/yy
          /// </summary>
          /// <example>
          /// Allows: 01/05/05, 12/30/99, 04/11/05
          /// Does not allow: 01/05/2000, 2/2/02
          /// </example> 
          public const string DATE_MM_DD_YY = @"^(1[0-2]|0[1-9])/(([1-2][0-9]|3[0-1]|0[1-9])/dd)$"; 


          /**//// <summary>
          /// This matches a date in the format mm/yy
          /// </summary>
          /// <example>
          /// Allows: 01/05, 11/05, 04/99
          /// Does not allow: 1/05, 13/05, 00/05
          /// </example>
          public const string DATE_MM_YY = @"^((0[1-9])|(1[0-2]))/(d{2})$";

          
          /**//// <summary>
          ///     This matches only numbers(no decimals)
          /// </summary>
          /// <example>
          /// Allows: 0, 1, 123, 4232323, 1212322
          /// </example>
          public const string IS_NUMBER_ONLY = @"^([1-9]d*)$|^0$";
         
          /**//// <summary>
          /// This matches any string with only alpha characters upper or lower case(A-Z)
          /// </summary>
          /// <example>
          /// Allows: abc, ABC, abCd, AbCd
          /// Does not allow: A C, abc!, (a,b)
          /// </example>
          public const string IS_ALPHA_ONLY = @"^[a-zA-Z]+$"; 

          /**//// <summary>
          /// This matches any string with only upper case alpha character(A-Z)
          /// </summary>
          public const string IS_UPPER_CASE = @"^[A-Z]+$";
          
          /**//// <summary>
          /// This matches any string with only lower case alpha character(A-Z)
          /// </summary>
          public const string IS_LOWER_CASE = @"^[a-z]+$";
          
          /**//// <summary>
          /// Ensures the string only contains alpha-numeric characters, and
          /// not punctuation, spaces, line breaks, etc.
          /// </summary>
          /// <example>
          /// Allows: ab2c, 112ABC, ab23Cd
          /// Does not allow: A C, abc!, a.a
          /// </example>
          public const string IS_ALPHA_NUMBER_ONLY = @"^[a-zA-Z0-9]+$";

          /**//// <summary>
          /// Validates US Currency.  Requires $ sign
          /// Allows for optional commas and decimal. 
          /// No leading zeros. 
          /// </summary>
          /// <example>Allows: $100,000 or $10000.00 or $10.00 or $.10 or $0 or $0.00
          /// Does not allow: $0.10 or 10.00 or 10,000</example>
          public const string IS_US_CURRENCY = @"^$(([1-9]d*|([1-9]d{0,2}(,d{3})*))(.d{1,2})?|(.d{1,2}))$|^$[0](.00)?$";

          /**//// <summary>
          /// Matches major credit cards including: Visa (length 16, prefix 4); 
          /// Mastercard (length 16, prefix 51-55);
          /// Diners Club/Carte Blanche (length 14, prefix 36, 38, or 300-305); 
          /// Discover (length 16, prefix 6011); 
          /// American Express (length 15, prefix 34 or 37). 
          /// Saves the card type as a named group to facilitate further validation 
          /// against a "card type" checkbox in a program. 
          /// All 16 digit formats are grouped 4-4-4-4 with an optional hyphen or space 
          /// between each group of 4 digits. 
          /// The American Express format is grouped 4-6-5 with an optional hyphen or space 
          /// between each group of digits. 
          /// Formatting characters must be consistant, i.e. if two groups are separated by a hyphen, 
          /// all groups must be separated by a hyphen for a match to occur.
          /// </summary>
          public const string CREDIT_CARD = @"^(?:(?<Visa>4d{3})|(?<Mastercard>5[1-5]d{2})|(?<Discover>6011)|(?<DinersClub>(?:3[68]d{2})|(?:30[0-5]d))|(?<AmericanExpress>3[47]d{2}))([ -]?)(?(DinersClub)(?:d{6}d{4})|(?(AmericanExpress)(?:d{6}d{5})|(?:d{4}d{4}d{4})))$";

          /**//// <summary>
          /// Matches social security in the following format xxx-xx-xxxx
          /// where x is a number
          /// </summary>
          /// <example>
          /// Allows: 123-45-6789, 232-432-1212
          /// </example>
          public const string SOCIAL_SECURITY = @"^d{3}-d{2}-d{4}$";

          /**//// <summary>
          /// Matches x,x where x is a name, spaces are only allowed between comma and name
          /// </summary>
          /// <example>
          /// Allows: christophersen,eric; christophersen, eric
          /// Not allowed: christophersen ,eric;
          /// </example>
          public const string NAME_COMMA_NAME = @"^[a-zA-Z]+,s?[a-zA-Z]+$";
            
          private Patterns()
          {
          }

          /**//// <summary>
          /// Checks to see if the passed input has the passed pattern
          /// </summary>
          /// <param name="pattern">The pattern to use</param>
          /// <param name="input">The input to check</param>
          /// <returns>True if the input has the pattern, false otherwise</returns>
          public static bool HasPattern( string pattern, string input )
          {
             Regex regEx = new Regex(pattern);
             return regEx.IsMatch(input);
          }

          /**//// <summary>
          /// Checks the passed input to make sure it has all the patterns in the 
          /// passed patterns array
          /// </summary>
          /// <param name="patterns">Array of patterns</param>
          /// <param name="input">String value to check</param>
          /// <returns>True if the input has all of the patterns, false otherwise.</returns>
          public static bool HasPatterns(string[] patterns, string input)
          {
             for (int i = 0; i < patterns.Length; i++)
             {
              if (Patterns.HasPattern(patterns[i], input) == false)
                  return false;
             }

             return true;
          }
        }
    }
  • 相关阅读:
    bzoj1083: [SCOI2005]繁忙的都市 瓶颈生成树
    Codeforces Round #344 (Div. 2)C. Report
    Wannafly挑战赛14E无效位置
    Codeforces Round #378 (Div. 2)F
    1059: [ZJOI2007]矩阵游戏 二分图匹配
    Educational Codeforces Round 42 (Rated for Div. 2)F
    bzo1016: [JSOI2008]最小生成树计数
    bzoj1009: [HNOI2008]GT考试 ac自动机+矩阵快速幂
    bzoj1070: [SCOI2007]修车
    table表格frame属性
  • 原文地址:https://www.cnblogs.com/Alex80/p/8947870.html
Copyright © 2011-2022 走看看