正則表達式 是一種匹配輸入文本的模式。
.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](?>A+B+) | “1ABB 3ABBC 5AB 5AC” 中的 “1ABB”、 “3ABB” 和 “5AB” |
4.1 (?= subexpression) 詳解
這裏實際上是這樣的:
-
首先查看下 subexpression 在原來字符串中是否存在
-
如果存在,則記錄下 subexpression 在原來字符串中的初始位置:
比如我要在 “abcdefg” 中查詢 “bc”,那位置就是 1
-
然後這個 subexpression 並不會進行返回:
所以 a(?=bc) 在 “abcdefg” 中返回的是 “a”,而不是 “abc”
-
最重要的是,由於返回的是位置,所以如果要再後面添加繼續匹配的內容:
比如 a(?=bc)d 在 “abcdefg” 中是比配不到的,需要寫成 a(?=bc)b,最終匹配成功的是 “ab”
4.2 (?! subexpression) 詳解
這裏同樣是匹配到一個不滿足 subexpression 的位置:
比如 “unsure sure unity used” 中匹配 \b(?!un)\w+\b
- 首先匹配 \b ,可以看到 4 個單詞都可以匹配上
- 然後匹配 (?!un),也就是單詞邊界後面跟着的不能是 un,也就是這個單詞不能是 un 開頭,所以 unsure 和 unity 就被排除了
- 之後再匹配 \w,其實並不是從單詞的第 2 個字母開始匹配(序號從 0 開始算),而是從第 0 個字母開始匹配,所以我們得到的是 sure 和 used,而不是 re 和 ed
4.3 (?<=subexpression) 詳解
對照前面來看, (?= subexpression) 取得的是匹配到的 subexpression 在原字符串中的起始位置,這裏 (?<=subexpression) 取得的是匹配到的終點位置。
比如在 “1851 1999 1950 1905 2003” 匹配 (?<=19)\d{2}\b:
- 首先匹配 (?<=19),找到了 3 個 “19”
- 然後我們得到的是這 3 個 “19” 的結束位置:6,11,16
- 然後從 3 個位置往後去尋找 \d{2}\b,所以找到了 “99”,“50”,“05”
另一種理解思路:
- 先匹配 \d{2}\b,找到 “51”,“99”,“50”,“05”,“03”
- 然後往前匹配 (?<=19),匹配到了也不顯示,所以結果是 “99”,“50”,“05”
4.4 (?<!subexpression) 詳解
首先在原字符串中匹配 subexpression,匹配到以後記錄下終點位置,後面的從終點位置往後進行匹配。
比如在 “Hi woman Hi man” 中匹配 (?<!wo)man\b:
- 首先匹配 man\b,找到 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” 的問題
- 在 “aaaaa aaaad” 中匹配 (\w)\1+.\b
- 首先 (\w) 匹配到所有的字母
- 然後 \1 表示再匹配一次,說明是兩個重複的字母
- 然後 + 表示前面的匹配 一次或多次,說明至少 2 個重複字母
- 到這裏,我們匹配上的是 “aaaaa” 和 “aaaa”
- 然後 . 匹配任何字符(包含空格),匹配上 “aaaaa ” 和 “aaaad”
- 然後 \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>
- 首先通過 (?<c>\w),要匹配一個 \w,同時把這個匹配規則存儲到 <c> 中
- 後面再匹配一個 k
- 然後,後面再通過 \k<c> 反引用存儲在 <c> 中的 \w(需要和前面 \w 匹配到的字符相同)
- 最終得到了 eke
通過 \ number 的方式,(\w)k\1,可以得到同樣的效果:
- 首先通過 (\w) 匹配一個 \w,同時存儲到 1 位置
- 然後在匹配一個 k
- 然後通過 \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