為了能夠讓同學們更好地理解如何在C#環境中使用正則表達式,錯新技術小編我寫出一些對你來說可能有用的正則表達式,這些表達式在其他的環境中都被使用過,一篇用于C#中很好的正則表達式獻給大家,希望能夠對你有所幫助。
羅馬數字
string p1 = "^m*(d?c{0,3}|c[dm])" + "(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])$";
string t1 = "vii";
Match m1 = Regex.Match(t1, p1);
交換前二個單詞
string t2 = "the quick brown fox";
string p2 = @"(/S+)(/s+)(/S+)";
Regex x2 = new Regex(p2);
string r2 = x2.Replace(t2, "$3$2$1", 1);
關健字=值
string t3 = "myval = 3";
string p3 = @"(/w+)/s*=/s*(.*)/s*$";
Match m3 = Regex.Match(t3, p3);
實現每行80個字符
string t4 = "********************"
+ "******************************"
+ "******************************";
string p4 = ".{80,}";
Match m4 = Regex.Match(t4, p4);
月/日/年 小時:分:秒的時間格式
string t5 = "01/01/01 16:10:01";
string p5 = @"(/d+)/(/d+)/(/d+) (/d+):(/d+):(/d+)";
Match m5 = Regex.Match(t5, p5);
改變目錄(僅適用于Windows平臺)
string t6 = @"C:/Documents and Settings/user1/Desktop/";
string r6 = Regex.Replace(t6,@"http://user1//", @"http://user2//");
擴展16位轉義符
string t7 = "%41"; // capital A
string p7 = "%([0-9A-Fa-f][0-9A-Fa-f])";
string r7 = Regex.Replace(t7, p7, HexConvert);
刪除C語言中的注釋(有待完善)
string t8 = @"
/*
* 傳統風格的注釋
*/
";
string p8 = @"
//* # 匹配注釋開始的定界符
.*? # 匹配注釋
/*/ # 匹配注釋結束定界符
";
string r8 = Regex.Replace(t8, p8, "", "xs");
刪除字符串中開始和結束處的空格
string t9a = " leading";
string p9a = @"^/s+";
string r9a = Regex.Replace(t9a, p9a, "");
string t9b = "trailing ";
string p9b = @"/s+$";
string r9b = Regex.Replace(t9b, p9b, "");
在字符/后添加字符n,使之成為真正的新行
string t10 = @"/ntest/n";
string r10 = Regex.Replace(t10, @"http://n", "/n");
轉換IP地址
string t11 = "55.54.53.52";
string p11 = "^" +
@"([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])" +
"$";
Match m11 = Regex.Match(t11, p11);
刪除文件名包含的路徑
string t12 = @"c:/file.txt";
string p12 = @"^.*//";
string r12 = Regex.Replace(t12, p12, "");
聯接多行字符串中的行
string t13 = @"this is
a split line";
string p13 = @"/s*/r?/n/s*";
string r13 = Regex.Replace(t13, p13, " ");
提取字符串中的所有數字
string t14 = @"
test 1
test 2.3
test 47
";
string p14 = @"(/d+/.?/d*|/./d+)";
MatchCollection mc14 = Regex.Matches(t14, p14);
找出所有的大寫字母
string t15 = "This IS a Test OF ALL Caps";
string p15 = @"(/b[^/Wa-z0-9_]+/b)";
MatchCollection mc15 = Regex.Matches(t15, p15);
找出小寫的單詞
string t16 = "This is A Test of lowercase";
string p16 = @"(/b[^/WA-Z0-9_]+/b)";
MatchCollection mc16 = Regex.Matches(t16, p16);
找出第一個字母為大寫的單詞
string t17 = "This is A Test of Initial Caps";
string p17 = @"(/b[^/Wa-z0-9_][^/WA-Z0-9_]*/b)";
MatchCollection mc17 = Regex.Matches(t17, p17);
找出簡單的HTML語言中的鏈接
string t18 = @"
first tag text
next tag text
";
string p18 = @"]*?HREF/s*=/s*[""']?" + @"([^'"" >]+?)[ '""]?>";
MatchCollection mc18 = Regex.Matches(t18, p18, "si"); [^>
以上就是錯新技術小編分享的用于C#中很好的正則表達式,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答