C# 正則表示式過濾指定的字串
阿新 • • 發佈:2019-01-09
[\w+]表示匹配數字、字母、下劃線和加號本身字元 [\w]+和\w+沒有區別,都是匹配數字和字母下劃線的多個字元 string str = @"testtesttesttest,@test:1。testtesttest,@test:2。testtesttest,@test:23。"; Regex reg = new Regex(@"@\w+:\d{1}"); //d{x} x是數字的個數 \w+ == [\w]+ foreach (Match m in reg.Matches(str)) { Console.WriteLine(m.Value); } /// <summary> /// 判斷傳入的值是中文字元 /// </summary> /// <param name="obj">漢字字元</param> /// <returns>count</returns> public static int StringToCh(object obj) { string ptn = "[\u4e00-\u9fa5]+"; int count = 0; Regex r = new Regex(ptn, RegexOptions.ECMAScript); foreach (Match m in r.Matches(ObjToString(obj))) { count++; } return count; } /// <summary> /// 判斷傳入的值是英文字元 /// </summary> /// <param name="obj">英文字元</param> /// <returns>count</returns> public static int StringToEn(object obj) { string ptn = "[a-zA-Z\\s]+"; int count = 0; Regex r = new Regex(ptn, RegexOptions.ECMAScript); foreach (Match m in r.Matches(ObjToString(obj))) { count++; } return count; }