C# 正则表达式详解(学习心得 25)

正则表达式 是一种匹配输入文本的模式。

.Net 框架提供了允许这种匹配的正则表达式引擎。

使用以下字符,运算符,结构,来定义正则表达式:

  • 转义字符
  • 字符类
  • 定位点
  • 分组构造
  • 限定符
  • 反向引用构造
  • 备用构造
  • 替换
  • 杂项构造

一、转义字符

转义字符列表:

转义字符 描述 模式 匹配
\a 与报警 (bell) 符 \u0007 匹配。 \a “Warning!” + ‘\u0007’ 中的 “\u0007”
\b 在字符类中,与退格键 \u0008 匹配。 [\b]{3,} “\b\b\b\b” 中的 “\b\b\b\b”
\t 与制表符 \u0009 匹配。 (\w+)\t “Name\tAddr\t” 中的 “Name\t” 和 “Addr\t”
\r 与回车符 \u000D 匹配。(\r 与换行符 \n 不是等效的。) \r\n(\w+) “\r\nHello\nWorld.” 中的 “\r\nHello”
\v 与垂直制表符 \u000B 匹配。 [\v]{2,} “\v\v\v” 中的 “\v\v\v”
\f 与换页符 \u000C 匹配。 [\f]{2,} “\f\f\f” 中的 “\f\f\f”
\n 与换行符 \u000A 匹配。 \r\n(\w+) “\r\nHello\nWorld.” 中的 “\r\nHello”
\e 与转义符 \u001B 匹配。 \e “\x001B” 中的 “\x001B”
\ nnn 使用八进制表示形式指定一个字符(nnn 由二到三位数字组成)。 \w\040\w “a bc d” 中的 “a b” 和 “c d”
\x nn 使用十六进制表示形式指定字符(nn 恰好由两位数字组成)。 \w\x20\w “a bc d” 中的 “a b” 和 “c d”
\c X \c x 匹配 X 或 x 指定的 ASCII 控件字符,其中 X 或 x 是控件字符的字母。 \cC “\x0003” 中的 “\x0003” (Ctrl-C)
\u nnnn 使用十六进制表示形式匹配一个 Unicode 字符(由 nnnn 表示的四位数)。 \w\u0020\w “a bc d” 中的 “a b” 和 “c d”
** 在后面带有不识别的转义字符时,与该字符匹配。 \d+[+-x*]\d+\d+[+-x*\d+ “(2+2) * 39″ 中的 “2+2” 和 “39″

二、字符类

字符类 描述 模式 匹配
[character_group] 匹配 character_group 中的任何单个字符。 默认情况下,匹配区分大小写。 [mn] “mat” 中的 “m”,”moon” 中的 “m” 和 “n”
[^character_group] 非:与不在 character_group 中的任何单个字符匹配。 默认情况下,character_group 中的字符区分大小写。 [^aei] “avail” 中的 “v” 和 “l”
[ first – last ] 字符范围:与从 first 到 last 的范围中的任何单个字符匹配。 [b-d] [b-d]irds 可以匹配 Birds、 Cirds、 Dirds
+ 匹配一个或者多个 A+ AAAB 可以匹配 AAA
. 通配符:与除 \n 之外的任何单个字符匹配。 若要匹配原意句点字符(. 或 \u002E),您必须在该字符前面加上转义符 (.)。 a.e “have” 中的 “ave”, “mate” 中的 “ate”
\p{ name } name 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。 \p{Lu} “City Lights” 中的 “C” 和 “L”
\P{ name } 与不在 name 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。 \P{Lu} “City” 中的 “i”、 “t” 和 “y”
\w 与任何单词字符匹配。 \w “Room#1” 中的 “R”、 “o”、 “m” 和 “1”
\W 与任何非单词字符匹配。 \W “Room#1” 中的 “#”
\s 与任何空白字符匹配。 \w\s “ID A1.3” 中的 “D “
\S 与任何非空白字符匹配。 \s\S “int __ctr” 中的 ” _”
\d 与任何十进制数字匹配。 \d “4 = IV” 中的 “4”
\D 匹配不是十进制数的任意字符。 \D “4 = IV” 中的 ” “、 “=”、 ” “、 “I” 和 “V”

关于 \p{ name }

\p{ name } 筛选目标
\p{L} or \p{Letter}: any kind of letter from any language.
\p{Ll} or \p{Lowercase_Letter}: a lowercase letter that has an uppercase variant.
\p{Lu} or \p{Uppercase_Letter}: an uppercase letter that has a lowercase variant.
\p{Lt} or \p{Titlecase_Letter}: a letter that appears at the start of a word when only the first letter of the word is capitalized.
\p{L&} or \p{Letter&}: a letter that exists in lowercase and uppercase variants (combination of Ll, Lu and Lt).
\p{Lm} or \p{Modifier_Letter}: a special character that is used like a letter.
\p{Lo} or \p{Other_Letter}: a letter or ideograph that does not have lowercase and uppercase variants.
\p{M} or \p{Mark}: a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.).
\p{Mn} or \p{Non_Spacing_Mark}: a character intended to be combined with another character without taking up extra space (e.g. accents, umlauts, etc.).
\p{Mc} or \p{Spacing_Combining_Mark}: a character intended to be combined with another character that takes up extra space (vowel signs in many Eastern languages).
\p{Me} or \p{Enclosing_Mark}: a character that encloses the character is is combined with (circle, square, keycap, etc.).
\p{Z} or \p{Separator}: any kind of whitespace or invisible separator.
\p{Zs} or \p{Space_Separator}: a whitespace character that is invisible, but does take up space.
\p{Zl} or \p{Line_Separator}: line separator character U+2028.
\p{Zp} or \p{Paragraph_Separator}: paragraph separator character U+2029.
\p{S} or \p{Symbol}: math symbols, currency signs, dingbats, box-drawing characters, etc..
\p{Sm} or \p{Math_Symbol}: any mathematical symbol.
\p{Sc} or \p{Currency_Symbol}: any currency sign.
\p{Sk} or \p{Modifier_Symbol}: a combining character (mark) as a full character on its own.
\p{So} or \p{Other_Symbol}: various symbols that are not math symbols, currency signs, or combining characters.
\p{N} or \p{Number}: any kind of numeric character in any script.
\p{Nd} or \p{Decimal_Digit_Number}: a digit zero through nine in any script except ideographic scripts.
\p{Nl} or \p{Letter_Number}: a number that looks like a letter, such as a Roman numeral.
\p{No} or \p{Other_Number}: a superscript or subscript digit, or a number that is not a digit 0..9 (excluding numbers from ideographic scripts).
\p{P} or \p{Punctuation}: any kind of punctuation character.
\p{Pd} or \p{Dash_Punctuation}: any kind of hyphen or dash.
\p{Ps} or \p{Open_Punctuation}: any kind of opening bracket.
\p{Pe} or \p{Close_Punctuation}: any kind of closing bracket.
\p{Pi} or \p{Initial_Punctuation}: any kind of opening quote.
\p{Pf} or \p{Final_Punctuation}: any kind of closing quote.
\p{Pc} or \p{Connector_Punctuation}: a punctuation character such as an underscore that connects words.
\p{Po} or \p{Other_Punctuation}: any kind of punctuation character that is not a dash, bracket, quote or connector.
\p{C} or \p{Other}: invisible control characters and unused code points.
\p{Cc} or \p{Control}: an ASCII 0x00..0x1F or Latin-1 0x80..0x9F control character.
\p{Cf} or \p{Format}: invisible formatting indicator.
\p{Co} or \p{Private_Use}: any code point reserved for private use.
\p{Cs} or \p{Surrogate}: one half of a surrogate pair in UTF-16 encoding.
\p{Cn} or \p{Unassigned}: any code point to which no character has been assigned.

使用 \p{ name } 匹配语言:

\p{Common}
\p{Arabic}
\p{Armenian}
\p{Bengali}
\p{Bopomofo}
\p{Braille}
\p{Buhid}
\p{CanadianAboriginal}
\p{Cherokee}
\p{Cyrillic}
\p{Devanagari}
\p{Ethiopic}
\p{Georgian}
\p{Greek}
\p{Gujarati}
\p{Gurmukhi}
\p{Han} 匹配汉语字符
\p{Hangul}
\p{Hanunoo}
\p{Hebrew}
\p{Hiragana}
\p{Inherited}
\p{Kannada}
\p{Katakana}
\p{Khmer}
\p{Lao}
\p{Latin}
\p{Limbu}
\p{Malayalam}
\p{Mongolian}
\p{Myanmar}
\p{Ogham}
\p{Oriya}
\p{Runic}
\p{Sinhala}
\p{Syriac}
\p{Tagalog}
\p{Tagbanwa}
\p{TaiLe}
\p{Tamil}
\p{Telugu}
\p{Thaana}
\p{Thai}
\p{Tibetan}
\p{Yi}

三、定位点

断言 描述 模式 匹配
^ 匹配必须从字符串或一行的开头开始。 ^\d{3} “567-777-” 中的 “567”
$ 匹配必须出现在字符串的末尾或出现在行或字符串末尾的 \n 之前。 -\d{4}$ “8-12-2012” 中的 “-2012”
\A 匹配必须出现在字符串的开头。 \A\w{4} “Code-007-” 中的 “Code”
\Z 匹配必须出现在字符串的末尾或出现在字符串末尾的 \n 之前。 -\d{3}\Z “Bond-901-007” 中的 “-007”
\z 匹配必须出现在字符串的末尾。 -\d{3}\z “-901-333” 中的 “-333”
\G 匹配必须出现在上一个匹配结束的地方。表示连续性 \G(\d) “(1)(3)(5)[7](9)” 中的 “(1)”、 “(3)” 和 “(5)”
\b 匹配一个单词边界,也就是指单词和空格间的位置。 er\b 匹配”never”中的”er”,但不能匹配”verb”中的”er”。
\B 匹配非单词边界。 er\B 匹配”verb”中的”er”,但不能匹配”never”中的”er”。

四、分组构造

分组构造 描述 模式 匹配
( subexpression ) 捕获匹配的子表达式并将其分配到一个从零开始的序号中。 (\w)\1 “deep” 中的 “ee”
(?< name >subexpression) 将匹配的子表达式捕获到一个命名组中。 (?< double>\w)\k< double> “deep” 中的 “ee”
(?< name1 -name2 >subexpression) 定义平衡组定义。 (((?’Open'()[()])+((?’Close-Open’\))[\()])+)*(?(Open)(?!))$ “3+2^((1-3)(3-1))” 中的 “((1-3)(3-1))”
(?: subexpression) 定义非捕获组。 Write(?:Line)? “Console.WriteLine()” 中的 “WriteLine”
(?imnsx-imnsx:subexpression) 应用或禁用 subexpression 中指定的选项。 A\d{2}(?i:\w+)\b “A12xl A12XL a12xl” 中的 “A12xl” 和 “A12XL”
(?= subexpression) 零宽度正预测先行断言。 \w+(?=.) “He is. The dog ran. The sun is out.” 中的 “is”、 “ran” 和 “out”
(?! subexpression) 零宽度负预测先行断言。 \b(?!un)\w+\b “unsure sure unity used” 中的 “sure” 和 “used”
(?<=subexpression) 零宽度正回顾后发断言。 (?<=19)\d{2}\b “1851 1999 1950 1905 2003” 中的 “99”、”50″和 “05”
(?<! subexpression) 零宽度负回顾后发断言。 (?<!wo)man\b “Hi woman Hi man” 中的 “man”
(?> subexpression) 非回溯(也称为”贪婪”)子表达式。 13579 “1ABB 3ABBC 5AB 5AC” 中的 “1ABB”、 “3ABB” 和 “5AB”

4.1 (?= subexpression) 详解

这里实际上是这样的:

  1. 首先查看下 subexpression 在原来字符串中是否存在

  2. 如果存在,则记录下 subexpression 在原来字符串中的初始位置:

    比如我要在 “abcdefg” 中查询 “bc”,那位置就是 1

  3. 然后这个 subexpression 并不会进行返回:

    所以 a(?=bc) 在 “abcdefg” 中返回的是 “a”,而不是 “abc”

  4. 最重要的是,由于返回的是位置,所以如果要再后面添加继续匹配的内容:

    比如 a(?=bc)d 在 “abcdefg” 中是比配不到的,需要写成 a(?=bc)b,最终匹配成功的是 “ab”

4.2 (?! subexpression) 详解

这里同样是匹配到一个不满足 subexpression 的位置:

比如 “unsure sure unity used” 中匹配 \b(?!un)\w+\b

  1. 首先匹配 \b ,可以看到 4 个单词都可以匹配上
  2. 然后匹配 (?!un),也就是单词边界后面跟着的不能是 un,也就是这个单词不能是 un 开头,所以 unsure 和 unity 就被排除了
  3. 之后再匹配 \w,其实并不是从单词的第 2 个字母开始匹配(序号从 0 开始算),而是从第 0 个字母开始匹配,所以我们得到的是 sure 和 used,而不是 re 和 ed

4.3 (?<=subexpression) 详解

对照前面来看, (?= subexpression) 取得的是匹配到的 subexpression 在原字符串中的起始位置,这里 (?<=subexpression) 取得的是匹配到的终点位置。

比如在 “1851 1999 1950 1905 2003” 匹配 (?<=19)\d{2}\b:

  1. 首先匹配 (?<=19),找到了 3 个 “19”
  2. 然后我们得到的是这 3 个 “19” 的结束位置:6,11,16
  3. 然后从 3 个位置往后去寻找 \d{2}\b,所以找到了 “99”,“50”,“05”

另一种理解思路:

  1. 先匹配 \d{2}\b,找到 “51”,“99”,“50”,“05”,“03”
  2. 然后往前匹配 (?<=19),匹配到了也不显示,所以结果是 “99”,“50”,“05”

4.4 (?<!subexpression) 详解

首先在原字符串中匹配 subexpression,匹配到以后记录下终点位置,后面的从终点位置往后进行匹配。

比如在 “Hi woman Hi man” 中匹配 (?<!wo)man\b:

  1. 首先匹配 man\b,找到 2 个地方
  2. 然后往前看 (?<!wo),只有一个地方满足,最后返回 “man”

4.5 (?> subexpression) 详解

官方文档的解释是,这里用 (?> subexpression) 这种表示不回溯。

比如:在 “aaaaa” 中匹配 (?>(\w)\1+)a\b 就不会匹配成功,而使用回溯机制即匹配 (\w)\1+a\b,就可以匹配成功得到 “aaaaa”。

这里其实遇到个问题:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "aaaaa aaaad";
        string pattern = @"(\w)\1+.\b";

        foreach (Match match in Regex.Matches(input, pattern))
            Console.WriteLine(match.Value);
    }
}

运行结果:

回溯情况:
aaaaa 
aaaad
不回溯情况:
aaaaa 
aaaad

但是按照官方文档的意思,由于不回溯,所以 “aaaaa” 不会匹配成功才对。

尝试如下:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "aaaaa";
        string noback_pattern = @"(\w)\1+.\b";

        Console.WriteLine("回溯情况:");
        foreach (Match match in Regex.Matches(input, noback_pattern))
            Console.WriteLine(match.Value);

        string back_pattern = @"(?>(\w)\1+).\b";
        Console.WriteLine("不回溯情况:");
        foreach (Match match in Regex.Matches(input, back_pattern))
            Console.WriteLine(match.Value);
    }
}

运行结果:

回溯情况:
aaaaa
不回溯情况:

始终搞不明白为什么以上两个例子中的结果会有这种差异!有待研究!

后记:总算搞明白了,这里不是 “回溯/不回溯”出了问题,而是 “\b” 的问题

  1. 在 “aaaaa aaaad” 中匹配 (\w)\1+.\b
  2. 首先 (\w) 匹配到所有的字母
  3. 然后 \1 表示再匹配一次,说明是两个重复的字母
  4. 然后 + 表示前面的匹配 一次或多次,说明至少 2 个重复字母
  5. 到这里,我们匹配上的是 “aaaaa” 和 “aaaa”
  6. 然后 . 匹配任何字符(包含空格),匹配上 “aaaaa ” 和 “aaaad”
  7. 然后 \b 匹配单词边界(包含前边界和后边界),匹配上 “aaaaa (\b为后面aaaad的前边界)” 和 “aaaad(\b单词后边界)”

五、限定符

限定符 描述 模式 匹配
***** 匹配上一个元素零次或多次。 \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”

六、反向引用构造

以前匹配到的,方便后面继续匹配

反向引用构造 描述 模式 匹配
\ number 反向引用。 匹配编号子表达式的值。 (\w)\1 “seek” 中的 “ee”
\k< name > 命名反向引用。 匹配命名表达式的值。 (?< char>\w)\k< char> “seek” 中的 “ee”

比如:”seeeke” 中我们要匹配 “eke”,则可以写成 (?<c>\w)k\k<c>

  1. 首先通过 (?<c>\w),要匹配一个 \w,同时把这个匹配规则存储到 <c> 中
  2. 后面再匹配一个 k
  3. 然后,后面再通过 \k<c> 反引用存储在 <c> 中的 \w(需要和前面 \w 匹配到的字符相同)
  4. 最终得到了 eke

通过 \ number 的方式,(\w)k\1,可以得到同样的效果:

  1. 首先通过 (\w) 匹配一个 \w,同时存储到 1 位置
  2. 然后在匹配一个 k
  3. 然后通过 \1,再次匹配一个 \w(需要和前面 \w 匹配到的字符相同)

七、备用构造

备用构造用于修改正则表达式以启用 either/or 匹配。

备用构造 描述 模式 匹配
| 匹配以竖线 (|) 字符分隔的任何一个元素。 th(e|is|at) “this is the day. ” 中的 “the” 和 “this”
(?( expression )yes | no ) 如果正则表达式模式由 expression 匹配指定,则匹配 yes;否则匹配可选的 no 部分。 expression 被解释为零宽度断言。 (?(A)A\d{2}\b|\b\d{3}\b) “A10 C103 910” 中的 “A10” 和 “910”
(?( name )yes | no ) 如果 name 或已命名或已编号的捕获组具有匹配,则匹配 yes;否则匹配可选的 no (?< quoted>”)?(?(quoted).+?”|\S+\s) “Dogs.jpg “Yiska playing.jpg”” 中的 Dogs.jpg 和 “Yiska playing.jpg”

八、替换

替换是替换模式中使用的正则表达式。

字符 描述 模式 替换模式 输入字符串 结果字符串
**$**number 替换按组 number 匹配的子字符串。 \b(\w+)(\s)(\w+)\b $3$2$1 “one two” “two one”
${name} 替换按命名组 name 匹配的子字符串。 \b(?< word1>\w+)(\s)(?< word2>\w+)\b {word2} {word1} “one two” “two one”
$$ 替换字符”$”。 \b(\d+)\s?USD $$$1 “103 USD” “$103”
$& 替换整个匹配项的一个副本。 ($(\d(.+\d+)?){1}) **$& “$1.30” $1.30
$` 替换匹配前的输入字符串的所有文本。 B+ $` “AABBCC” “AAAACC”
$’ 替换匹配后的输入字符串的所有文本。 B+ $’ “AABBCC” “AACCCC”
$+ 替换最后捕获的组。 B+(C+) $+ “AABBCCDD” AACCDD
$_ 替换整个输入字符串。 B+ $_ “AABBCC” “AAAABBCCCC”

九、杂项构造

构造 描述 实例
(?imnsx-imnsx) 在模式中间对诸如不区分大小写这样的选项进行设置或禁用。 \bA(?i)b\w+\b 匹配 “ABA Able Act” 中的 “ABA” 和 “Able”
(?#注释) 内联注释。该注释在第一个右括号处终止。 \bA(?#匹配以A开头的单词)\w+\b
(?x) # [行尾] 该注释以非转义的 # 开头,并继续到行的结尾。 (?x)\bA\w+\b#匹配以 A 开头的单词

十、Regex 类

Regex 类用于表示一个正则表达式。

常用方法:

序号 方法 & 描述
1 public bool IsMatch( string input ) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。
2 public bool IsMatch( string input, int startat ) 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中指定的开始位置开始。
3 public static bool IsMatch( string input, string pattern ) 指示指定的正则表达式是否在指定的输入字符串中找到匹配项。
4 public MatchCollection Matches( string input ) 在指定的输入字符串中搜索正则表达式的所有匹配项。
5 public string Replace( string input, string replacement ) 在指定的输入字符串中,把所有匹配正则表达式模式的所有匹配的字符串替换为指定的替换字符串。
6 public string[] Split( string input ) 把输入字符串分割为子字符串数组,根据在 Regex 构造函数中指定的正则表达式模式定义的位置进行分割。

10.1 例:匹配以 ‘S’ 开头的单词

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
   class Program
   {
      private static void showMatch(string text, string expr)
      {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc)
         {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args)
      {
         string str = "A Thousand Splendid Suns";

         Console.WriteLine("Matching words that start with 'S': ");
         showMatch(str, @"\bS\S*");
         Console.ReadKey();
      }
   }
}

运行结果:

Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

10.2 例:匹配以 ‘m’ 开头以 ‘e’ 结尾的单词

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
   class Program
   {
      private static void showMatch(string text, string expr)
      {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc)
         {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args)
      {
         string str = "make maze and manage to measure it";

         Console.WriteLine("Matching words start with 'm' and ends with 'e':");
         showMatch(str, @"\bm\S*e\b");
         Console.ReadKey();
      }
   }
}

运行结果:

Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure

10.3 例:替换掉多余的空格

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         string input = "Hello   World   ";
         string pattern = "\\s+";
         string replacement = " ";
         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);

         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String: {0}", result);    
         Console.ReadKey();
      }
   }
}

运行结果:

Original String: Hello   World   
Replacement String: Hello World   
Tags: