C#正則表達式匹配連續相同字符,如...aaa..bbb...11111...2222...

參考:https://blog.csdn.net/tao_sheng_yi_jiu/article/details/80366004

目的:匹配連續相同的3個數字或字母

string regExp = "(\\w)\1{2}";
//注意此處不要添加邊界符號(^和$)
string str = "!@$#12aaa3444da33dddd@#$%%$#";
MatchCollection matchSet2 = Regex.Matches(str, regExp);
foreach (Match aMatch2 in matchSet2)
{
    Console.WriteLine(aMatch2.Groups[0].Captures[0]);
}
Console.ReadKey();

// 探究regExp中\1和{2}的作用
// 設regExp ="(\\w)\n{2}";
/* \1作用
n=1, 匹配str中的aaa;
n=2, 匹配str中的444;
n=3, 匹配str中的ddd(前一個);
n=4, 匹配str中的ddd(後一個);
*/
/* {2}作用
regExp中{2}大括號裏面的2代表和前面的字符重複的個數,比如aaa,就是和第一個a後面跟着2個重複的a
\\w相當於[a-zA-Z0-9]
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章