為了能夠更好地理解如何在C#環(huán)境中使用正則表達式,我寫出一些對你來說可能有用的正則表達式,這些表達式在其他的環(huán)境中都被使用過,希望能夠?qū)δ阌兴鶐椭?/p>
羅馬數(shù)字
stringp1="^m*(d?c{0,3}|c[dm])"+"(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])$";
stringt1="vii";
Matchm1=Regex.Match(t1,p1);
交換前二個單詞
stringt2="thequickbrownfox";
stringp2=@"(/S+)(/s+)(/S+)";
Regexx2=newRegex(p2);
stringr2=x2.Replace(t2,"$3$2$1",1);
關(guān)健字=值
stringt3="myval=3";
stringp3=@"(/w+)/s*=/s*(.*)/s*$";
Matchm3=Regex.Match(t3,p3);
實現(xiàn)每行80個字符
stringt4="********************"
+"******************************"
+"******************************";
stringp4=".{80,}";
Matchm4=Regex.Match(t4,p4);
月/日/年小時:分:秒的時間格式
stringt5="01/01/0116:10:01";
stringp5=@"(/d+)/(/d+)/(/d+)(/d+):(/d+):(/d+)";
Matchm5=Regex.Match(t5,p5);
改變目錄(僅適用于Windows平臺)
stringt6=@"C:/DocumentsandSettings/user1/Desktop/";
stringr6=Regex.Replace(t6,@"//user1//",@"//user2//");
擴展16位轉(zhuǎn)義符
stringt7="%41";//capitalA
stringp7="%([0-9A-Fa-f][0-9A-Fa-f])";
stringr7=Regex.Replace(t7,p7,HexConvert);
刪除C語言中的注釋(有待完善)
stringt8=@"
/*
*傳統(tǒng)風(fēng)格的注釋
*/
";
stringp8=@"
//*#匹配注釋開始的定界符
.*?#匹配注釋
/*/#匹配注釋結(jié)束定界符
";
stringr8=Regex.Replace(t8,p8,"","xs");
刪除字符串中開始和結(jié)束處的空格
stringt9a="leading";
stringp9a=@"^/s+";
stringr9a=Regex.Replace(t9a,p9a,"");
stringt9b="trailing";
stringp9b=@"/s+$";
stringr9b=Regex.Replace(t9b,p9b,"");
在字符/后添加字符n,使之成為真正的新行
stringt10=@"/ntest/n";
stringr10=Regex.Replace(t10,@"//n","/n");
轉(zhuǎn)換IP地址
stringt11="55.54.53.52";
stringp11="^"+
@"([01]?/d/d|2[0-4]/d|25[0-5])/."+
@"([01]?/d/d|2[0-4]/d|25[0-5])/."+
@"([01]?/d/d|2[0-4]/d|25[0-5])/."+
@"([01]?/d/d|2[0-4]/d|25[0-5])"+
"$";
Matchm11=Regex.Match(t11,p11);
刪除文件名包含的路徑
stringt12=@"c:/file.txt";
stringp12=@"^.*//";
stringr12=Regex.Replace(t12,p12,"");
聯(lián)接多行字符串中的行
stringt13=@"thisis
asplitline";
stringp13=@"/s*/r?/n/s*";
stringr13=Regex.Replace(t13,p13,"");
提取字符串中的所有數(shù)字
stringt14=@"
test1
test2.3
test47
";
stringp14=@"(/d+/.?/d*|/./d+)";
MatchCollectionmc14=Regex.Matches(t14,p14);
找出所有的大寫字母
stringt15="ThisISaTestOFALLCaps";
stringp15=@"(/b[^/Wa-z0-9_]+/b)";
MatchCollectionmc15=Regex.Matches(t15,p15);
找出小寫的單詞
stringt16="ThisisATestoflowercase";
stringp16=@"(/b[^/WA-Z0-9_]+/b)";
MatchCollectionmc16=Regex.Matches(t16,p16);
找出第一個字母為大寫的單詞
stringt17="ThisisATestofInitialCaps";
stringp17=@"(/b[^/Wa-z0-9_][^/WA-Z0-9_]*/b)";
MatchCollectionmc17=Regex.Matches(t17,p17);
找出簡單的HTML語言中的鏈接
stringt18=@"
firsttagtext
nexttagtext
";
stringp18=@"]*?HREF/s*=/s*[""']?"+@"([^'"">]+?)['""]?>";
MatchCollectionmc18=Regex.Matches(t18,p18,"si");
新聞熱點
疑難解答
圖片精選