常用正则收集
沙福林 2023-04-22 20:03:58
Java
工具类
正则
个人常用正则收集,有些的自己写的,有些的搬运的
# 前期提要
# 匹配时间 HH:mm:ss
"([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"
1
# 中文
[\\w\\u4E00-\\u9FA5\\uF900-\\uFA2D]
1
# 贪婪模式阻止
(.*?)
1
# 不创建组
(?:xxxx)
1
# 小写转大写
# 匹配字符串:
(.*),(.*)
# 替换正则
DICT_\U$2\E = "$2";
1
2
3
4
2
3
4
例如:用户性别,sys_user_sex
匹配正则:(.*),(.*),替换正则:DICT_\U$2\E = "$2";
最终替换效果为:DICT_SYS_USER_SEX = "sys_user_sex";
# 数字
有无符号+整数+小数
[+-]?(^0|[1-9]\\d*)(\\.\\d+)?
1
测试程序如下
@Test
public void test22(){
String regex = "[+-]?(^0|[1-9]\\d*)(\\.\\d+)?";
System.out.printf("0 %s\n","0".matches(regex));//0
System.out.printf("10 %s\n","10".matches(regex));//整数
System.out.printf("+10 %s\n","+10".matches(regex));//正整数
System.out.printf("-10 %s\n","-10".matches(regex));//负整数
System.out.printf("10.23 %s\n","10.23".matches(regex));//小数
System.out.printf("0.23 %s\n","0.23".matches(regex));//小数
System.out.printf("+10.23 %s\n","+10.23".matches(regex));//正小数
System.out.printf("-10.23 %s\n","-10.23".matches(regex));//负小数
//想要限制小数精度,直接把小数部分的\d+改为\d{精度}即可,例如限制两位小数精度则为"[+-]?(0|[1-9]\\d*)(\\.\\d{2})?"
System.out.println("异常数字验证=============================================");
System.out.printf("000 %s\n","000".matches(regex));//000
System.out.printf("00.1 %s\n","000".matches(regex));//00.1
System.out.printf("0. %s\n","000".matches(regex));//0.
System.out.printf(".0 %s\n","000".matches(regex));//.0
System.out.printf("11. %s\n","000".matches(regex));//11.
System.out.printf("-0 %s\n","-0".matches(regex));//-0
System.out.printf("+0 %s\n","+0".matches(regex));//+0
//想要限制小数精度,直接把小数部分的\d+改为\d{精度}即可,例如限制两位小数精度则为"[+-]?(^0|[1-9]\\d*)(\\.\\d{2})?"
regex = "[+-]?(^0|[1-9]\\d*)(\\.\\d{2})?";
System.out.println("想要限制小数精度=============================================");
System.out.printf("精度不够 10.2 %s\n","10.2".matches(regex));
System.out.printf("精度超出 10.2345 %s\n","10.2345".matches(regex));
System.out.printf("多个0也不行 00.23 %s\n","00.23".matches(regex));
System.out.printf("精度正好 10.23 %s\n","10.23".matches(regex));
System.out.printf("精度正好 0.23 %s\n","0.23".matches(regex));
}
0 true
10 true
+10 true
-10 true
10.23 true
0.23 true
+10.23 true
-10.23 true
异常数字验证=============================================
000 false
00.1 false
0. false
.0 false
11. false
-0 false
+0 false
想要限制小数精度=============================================
精度不够 10.2 false
精度超出 10.2345 false
多个0也不行 00.23 false
精度正好 10.23 true
精度正好 0.23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52