七、C#正则表达式匹配字符串
正则表达式可以快速判断所给字符串是否某种指定格式。这里将一些常用的方法封装进一个字符串工具类中。
1 public static class StringTool
2 {
3 /// <summary>
4 /// 判断字符串是否纯数字
5 /// </summary>
6 /// <param name="str"></param>
7 /// <returns></returns>
8 public static bool IsNumber(string str)
9 {
10 return Regex.IsMatch(str, @"^[0-9]+$");
11 }
12
13 /// <summary>
14 /// 判断字符串是否纯字母
15 /// </summary>
16 /// <param name="str"></param>
17 /// <returns></returns>
18 public static bool IsLetter(string str)
19 {
20 return Regex.IsMatch(str, @"^[A-Za-z]+$");
21 }
22
23 /// <summary>
24 /// 判断字符串是否字母或数字的组合
25 /// </summary>
26 /// <param name="str"></param>
27 /// <returns></returns>
28 public static bool IsLetterOrNumber(string str)
29 {
30 return Regex.IsMatch(str, @"(?i)^[0-9a-z]+$");
31 }
32
33 /// <summary>
34 /// 统计字符串中汉字个数
35 /// </summary>
36 /// <param name="str"></param>
37 /// <returns></returns>
38 public static int CountChinese(string str)
39 {
40 return str.Count(c => Regex.IsMatch(c.ToString(), @"^[\u4E00-\u9FA5]{0,}$"));
41 }
42
43 /// <summary>
44 /// 判断字符串是否纯中文
45 /// </summary>
46 /// <param name="str"></param>
47 /// <returns></returns>
48 public static bool IsChinese(string str)
49 {
50 return Regex.IsMatch(str, @"^[\u4e00-\u9fa5],{0,}$");
51 }
52
53 /// <summary>
54 /// 判断字符串中是否包含中文
55 /// </summary>
56 /// <param name="str"></param>
57 /// <returns></returns>
58 public static bool HasChinese(string str)
59 {
60 return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
61 }
62
63 /// <summary>
64 /// 统计字符串中全角字符个数
65 /// </summary>
66 /// <param name="str"></param>
67 /// <returns></returns>
68 public static int CountSbcCase(string str)
69 {
70 return Encoding.Default.GetByteCount(str) - str.Length;
71 }
72
73 /// <summary>
74 /// 判断字符串中是否包含全角字符
75 /// </summary>
76 /// <param name="str"></param>
77 /// <returns></returns>
78 public static bool HasSbcCase(string str)
79 {
80 return CountSbcCase(str) > 0;
81 }
82
83 /// <summary>
84 /// 统计字符串中半角字符个数
85 /// </summary>
86 /// <param name="str"></param>
87 /// <returns></returns>
88 public static int CountDbcCase(string str)
89 {
90 return str.Length - CountSbcCase(str);
91 }
92
93 /// <summary>
94 /// 判断字符串中是否包含半角字符
95 /// </summary>
96 /// <param name="str"></param>
97 /// <returns></returns>
98 public static bool HasDbcCase(string str)
99 {
100 return CountDbcCase(str) > 0;
101 }
102
103 /// <summary>
104 /// 判断字符串中是否符合邮箱格式
105 /// </summary>
106 /// <param name="str"></param>
107 /// <returns></returns>
108 public static bool IsEmail(string str)
109 {
110 return Regex.IsMatch(str, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
111 }
112 }


浙公网安备 33010602011771号