C#中的正則表達式網上摘抄

C#中的正則表達式網上摘抄

(1)「@」符號
符下兩ows表研究室的火熱,當晨在「@」雖然並不是C#正則表達式的「成員」,可是它常常與C#正則表達式出雙入對。「@」表示,跟在它後面的字符串是個「逐字字符串」,不是很好理解,舉個例子,如下兩個聲明是等效的:
string x="D:\\My Huang\\My Doc";
string y = @"D:\My Huang\My Doc";
事實上,若是按以下聲明,C#將會報錯,由於「\」在C#中用於實現轉義,如「\n」換行:
string x = "D:\My Huang\My Doc";正則表達式

(2)基本的語法字符。
\d 0-9的數字
\D \d的補集(以因此字符爲全集,下同),即全部非數字的字符
\w 單詞字符,指大小寫字母、0-9的數字、下劃線
\W \w的補集
\s 空白字符,包括換行符\n、回車符\r、製表符\t、垂直製表符\v、換頁符\f
\S \s的補集
. 除換行符\n外的任意字符
[…] 匹配[]內所列出的全部字符
[^…] 匹配非[]內所列出的字符
下面提供一些簡單的示例:ide

Code
string i = "\n";
string m = "3";
Regex r = new Regex(@"\D");
//同Regex r = new Regex("\\D");
//r.IsMatch(i)結果:true
//r.IsMatch(m)結果:falseblog

string i = "%";
string m = "3";
Regex r = new Regex("[a-z0-9]");
//匹配小寫字母或數字字符
//r.IsMatch(i)結果:false
//r.IsMatch(m)結果:true索引

(3)定位字符
「定位字符」所表明的是一個虛的字符,它表明一個位置,你也能夠直觀地認爲「定位字符」所表明的是某個字符與字符間的那個微小間隙。
^ 表示其後的字符必須位於字符串的開始處
$ 表示其前面的字符必須位於字符串的結束處
\b 匹配一個單詞的邊界
\B 匹配一個非單詞的邊界
另外,還包括:\A 前面的字符必須位於字符處的開始處,\z 前面的字符必須位於字符串的結束處,\Z 前面的字符必須位於字符串的結束處,或者位於換行符前
下面提供一些簡單的示例:文檔

Code
string i = "Live for nothing,die for something";
Regex r1 = new Regex("^Live for nothing,die for something$");
//r1.IsMatch(i) true
Regex r2 = new Regex("^Live for nothing,die for some$");
//r2.IsMatch(i) false
Regex r3 = new Regex("^Live for nothing,die for some");
//r3.IsMatch(i) true字符串

string i = @"Live for nothing,
die for something";//多行
Regex r1 = new Regex("^Live for nothing,die for something$");
Console.WriteLine("r1 match count:" + r1.Matches(i).Count);//0
Regex r2 = new Regex("^Live for nothing,die for something$", RegexOptions.Multiline);
Console.WriteLine("r2 match count:" + r2.Matches(i).Count);//0
Regex r3 = new Regex("^Live for nothing,\r\ndie for something$");
Console.WriteLine("r3 match count:" + r3.Matches(i).Count);//1
Regex r4 = new Regex("^Live for nothing,$");
Console.WriteLine("r4 match count:" + r4.Matches(i).Count);//0
Regex r5 = new Regex("^Live for nothing,$", RegexOptions.Multiline);
Console.WriteLine("r5 match count:" + r5.Matches(i).Count);//0
Regex r6 = new Regex("^Live for nothing,\r\n$");
Console.WriteLine("r6 match count:" + r6.Matches(i).Count);//0
Regex r7 = new Regex("^Live for nothing,\r\n$", RegexOptions.Multiline);
Console.WriteLine("r7 match count:" + r7.Matches(i).Count);//0
Regex r8 = new Regex("^Live for nothing,\r$");
Console.WriteLine("r8 match count:" + r8.Matches(i).Count);//0
Regex r9 = new Regex("^Live for nothing,\r$", RegexOptions.Multiline);
Console.WriteLine("r9 match count:" + r9.Matches(i).Count);//1
Regex r10 = new Regex("^die for something$");
Console.WriteLine("r10 match count:" + r10.Matches(i).Count);//0
Regex r11 = new Regex("^die for something$", RegexOptions.Multiline);
Console.WriteLine("r11 match count:" + r11.Matches(i).Count);//1
Regex r12 = new Regex("^");
Console.WriteLine("r12 match count:" + r12.Matches(i).Count);//1
Regex r13 = new Regex("$");
Console.WriteLine("r13 match count:" + r13.Matches(i).Count);//1
Regex r14 = new Regex("^", RegexOptions.Multiline);
Console.WriteLine("r14 match count:" + r14.Matches(i).Count);//2
Regex r15 = new Regex("$", RegexOptions.Multiline);
Console.WriteLine("r15 match count:" + r15.Matches(i).Count);//2
Regex r16 = new Regex("^Live for nothing,\r$\n^die for something$", RegexOptions.Multiline);
Console.WriteLine("r16 match count:" + r16.Matches(i).Count);//1
//對於一個多行字符串,在設置了Multiline選項以後,^和$將出現屢次匹配。get

string i = "Live for nothing,die for something";
string m = "Live for nothing,die for some thing";
Regex r1 = new Regex(@"\bthing\b");
Console.WriteLine("r1 match count:" + r1.Matches(i).Count);//0
Regex r2 = new Regex(@"thing\b");
Console.WriteLine("r2 match count:" + r2.Matches(i).Count);//2
Regex r3 = new Regex(@"\bthing\b");
Console.WriteLine("r3 match count:" + r3.Matches(m).Count);//1
Regex r4 = new Regex(@"\bfor something\b");
Console.WriteLine("r4 match count:" + r4.Matches(i).Count);//1
//\b一般用於約束一個完整的單詞string


(4)重複描述字符
「重複描述字符」是體現C#正則表達式「很好很強大」的地方之一:
{n} 匹配前面的字符n次
{n,} 匹配前面的字符n次或多於n次
{n,m} 匹配前面的字符n到m次
? 匹配前面的字符0或1次
+ 匹配前面的字符1次或多於1次
* 匹配前面的字符0次或式於0次
如下提供一些簡單的示例:it

Code
string x = "1024";
string y = "+1024";
string z = "1,024";
string a = "1";
string b="-1024";
string c = "10000";
Regex r = new Regex(@"^\+?[1-9],?\d{3}$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//1
Console.WriteLine("z match count:" + r.Matches(z).Count);//1
Console.WriteLine("a match count:" + r.Matches(a).Count);//0
Console.WriteLine("b match count:" + r.Matches(b).Count);//0
Console.WriteLine("c match count:" + r.Matches(c).Count);//0
//匹配1000到9999的整數。io


(5)擇一匹配
C#正則表達式中的 (|) 符號彷佛沒有一個專門的稱謂,姑且稱之爲「擇一匹配」吧。事實上,像[a-z]也是一種擇一匹配,只不過它只能匹配單個字符,而(|)則提供了更大的範圍,(ab|xy)表示匹配ab或匹配xy。注意「|」與「()」在此是一個總體。下面提供一些簡單的示例:

Code
string x = "0";
string y = "0.23";
string z = "100";
string a = "100.01";
string b = "9.9";
string c = "99.9";
string d = "99.";
string e = "00.1";
Regex r = new Regex(@"^\+?((100(.0+)*)|([1-9]?[0-9])(\.\d+)*)$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//1
Console.WriteLine("z match count:" + r.Matches(z).Count);//1
Console.WriteLine("a match count:" + r.Matches(a).Count);//0
Console.WriteLine("b match count:" + r.Matches(b).Count);//1
Console.WriteLine("c match count:" + r.Matches(c).Count);//1
Console.WriteLine("d match count:" + r.Matches(d).Count);//0
Console.WriteLine("e match count:" + r.Matches(e).Count);//0
//匹配0到100的數。最外層的括號內包含兩部分「(100(.0+)*)」,「([1-9]?[0-9])(\.\d+)*」,這兩部分是「OR」的關係,即正則表達式引擎會先嚐試匹配100,若是失敗,則嘗試匹配後一個表達式(表示[0,100)範圍中的數字)。


(6)特殊字符的匹配
下面提供一些簡單的示例:

Code
string x = "\\";
Regex r1 = new Regex("^\\\\$");
Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1
Regex r2 = new Regex(@"^\\$");
Console.WriteLine("r2 match count:" + r2.Matches(x).Count);//1
Regex r3 = new Regex("^\\$");
Console.WriteLine("r3 match count:" + r3.Matches(x).Count);//0
//匹配「\」

string x = "\"";
Regex r1 = new Regex("^\"$");
Console.WriteLine("r1 match count:" + r1.Matches(x).Count);//1
Regex r2 = new Regex(@"^""$");
Console.WriteLine("r2 match count:" + r2.Matches(x).Count);//1
//匹配雙引號

(7)組與非捕獲組
如下提供一些簡單的示例:

Code
string x = "Live for nothing,die for something";
string y = "Live for nothing,die for somebody";
Regex r = new Regex(@"^Live ([a-z]{3}) no([a-z]{5}),die \1 some\2$");
Console.WriteLine("x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//0
//正則表達式引擎會記憶「()」中匹配到的內容,做爲一個「組」,而且能夠經過索引的方式進行引用。表達式中的「\1」,用於反向引用表達式中出現的第一個組,即粗體標識的第一個括號內容,「\2」則依此類推。

string x = "Live for nothing,die for something";
Regex r = new Regex(@"^Live for no([a-z]{5}),die for some\1$");
if (r.IsMatch(x))
{
    Console.WriteLine("group1 value:" + r.Match(x).Groups[1].Value);//輸出:thing
}
//獲取組中的內容。注意,此處是Groups[1],由於Groups[0]是整個匹配的字符串,即整個變量x的內容。

string x = "Live for nothing,die for something";
Regex r = new Regex(@"^Live for no(?<g1>[a-z]{5}),die for some\1$");
if (r.IsMatch(x))
{
    Console.WriteLine("group1 value:" + r.Match(x).Groups["g1"].Value);//輸出:thing
}
//可根據組名進行索引。使用如下格式爲標識一個組的名稱(?<groupname>…)。

string x = "Live for nothing nothing";
Regex r = new Regex(@"([a-z]+) \1");
if (r.IsMatch(x))
{
    x = r.Replace(x, "$1");
    Console.WriteLine("var x:" + x);//輸出:Live for nothing
}
//刪除原字符串中重複出現的「nothing」。在表達式以外,使用「$1」來引用第一個組,下面則是經過組名來引用:
string x = "Live for nothing nothing";
Regex r = new Regex(@"(?<g1>[a-z]+) \1");
if (r.IsMatch(x))
{
    x = r.Replace(x, "${g1}");
    Console.WriteLine("var x:" + x);//輸出:Live for nothing
}

string x = "Live for nothing";
Regex r = new Regex(@"^Live for no(?:[a-z]{5})$");
if (r.IsMatch(x))
{
    Console.WriteLine("group1 value:" + r.Match(x).Groups[1].Value);//輸出:(空)
}
//在組前加上「?:」表示這是個「非捕獲組」,即引擎將不保存該組的內容。

(8)貪婪與非貪婪
正則表達式的引擎是貪婪,只要模式容許,它將匹配儘量多的字符。經過在「重複描述字符」(*,+)後面添加「?」,能夠將匹配模式改爲非貪婪。請看如下示例:

Code
string x = "Live for nothing,die for something";
Regex r1 = new Regex(@".*thing");
if (r1.IsMatch(x))
{
    Console.WriteLine("match:" + r1.Match(x).Value);//輸出:Live for nothing,die for something
}
Regex r2 = new Regex(@".*?thing");
if (r2.IsMatch(x))
{
    Console.WriteLine("match:" + r2.Match(x).Value);//輸出:Live for nothing
}

(9)回溯與非回溯
使用「(?>…)」方式進行非回溯聲明。因爲正則表達式引擎的貪婪特性,致使它在某些狀況下,將進行回溯以得到匹配,請看下面的示例:

Code
string x = "Live for nothing,die for something";
Regex r1 = new Regex(@".*thing,");
if (r1.IsMatch(x))
{
    Console.WriteLine("match:" + r1.Match(x).Value);//輸出:Live for nothing,
}
Regex r2 = new Regex(@"(?>.*)thing,");
if (r2.IsMatch(x))//不匹配
{
    Console.WriteLine("match:" + r2.Match(x).Value);
}
//在r1中,「.*」因爲其貪婪特性,將一直匹配到字符串的最後,隨後匹配「thing」,但在匹配「,」時失敗,此時引擎將回溯,並在「thing,」處匹配成功。
在r2中,因爲強制非回溯,因此整個表達式匹配失敗。

(10)正向預搜索、反向預搜索
正向預搜索聲明格式:正聲明 「(?=…)」,負聲明 「(?!...)」 ,聲明自己不做爲最終匹配結果的一部分,請看下面的示例:

Code
string x = "1024 used 2048 free";
Regex r1 = new Regex(@"\d{4}(?= used)");
if (r1.Matches(x).Count==1)
{
    Console.WriteLine("r1 match:" + r1.Match(x).Value);//輸出:1024
}
Regex r2 = new Regex(@"\d{4}(?! used)");
if (r2.Matches(x).Count==1)
{
    Console.WriteLine("r2 match:" + r2.Match(x).Value); //輸出:2048
}
//r1中的正聲明表示必須保證在四位數字的後面必須緊跟着「 used」,r2中的負聲明表示四位數字以後不能跟有「 used」。

反向預搜索聲明格式:正聲明「(?<=)」,負聲明「(?<!)」,聲明自己不做爲最終匹配結果的一部分,請看下面的示例:

Code
string x = "used:1024 free:2048";
Regex r1 = new Regex(@"(?<=used:)\d{4}");
if (r1.Matches(x).Count==1)
{
    Console.WriteLine("r1 match:" + r1.Match(x).Value);//輸出:1024
}
Regex r2 = new Regex(@"(?<!used:)\d{4}");
if (r2.Matches(x).Count==1)
{
    Console.WriteLine("r2 match:" + r2.Match(x).Value);//輸出:2048
}
//r1中的反向正聲明表示在4位數字以前必須緊跟着「used:」,r2中的反向負聲明表示在4位數字以前必須緊跟着除「used:」以外的字符串。

(11)十六進制字符範圍
正則表達式中,可使用 "\xXX" 和 "\uXXXX" 表示一個字符("X" 表示一個十六進制數)形式字符範圍:
\xXX       編號在 0到255 範圍的字符,好比:空格可使用 "\x20" 表示。
\uXXXX   任何字符可使用 "\u" 再加上其編號的4位十六進制數表示,好比:漢字可使用「[\u4e00-\u9fa5]」表示。


(12)對[0,100]的比較完備的匹配
下面是一個比較綜合的示例,對於匹配[0,100],須要特殊考慮的地方包括
*00合法,00.合法,00.00合法,001.100合法
*空字符串不合法,僅小數點不合法,大於100不合法
*數值是可帶後綴的,如「1.07f」表示該值爲一個float類型(未考慮)

Code
Regex r = new Regex(@"^\+?0*(?:100(\.0*)?|(\d{0,2}(?=\.\d)|\d{1,2}(?=($|\.$)))(\.\d*)?)$");
string x = "";
while (true)
{
    x = Console.ReadLine();
    if (x != "exit")
    {
        if (r.IsMatch(x))
        {
            Console.WriteLine(x + " succeed!");
        }
        else
        {
            Console.WriteLine(x + " failed!");
        }
    }
    else
    {
        break;
    }
}

(13)精確匹配有時候是困難的 有些需求要作到精確匹配比較困難,例如:日期、Url、Email地址等,其中一些你甚至須要研究一些專門的文檔寫出精確完備的表達式,對於這種狀況,只能退而求其次,保證比較精確的匹配。例如對於日期,能夠基於應用系統的實際狀況考慮一段較短的時間,或者對於像Email的匹配,能夠只考慮最多見的形式。

相關文章
相關標籤/搜索