Blackdogman’s blog

正则表达式

概念

懒惰匹配(匹配符合条件的最短的那条)

JAVA中正则表达的使用

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
//匹配正则字符串-方式1
public void fun(){
//定义正则表达式规则
Pattern p = Pattern.compile("正则表达式");

//匹配字符串
Matcher m = p.matcher("需要进行匹配的字符串");

//进行一个匹配(返回是否匹配成功)
boolean flag = m.matches();
}
//匹配正则字符串-方式2
public void fun2(){
//直接匹配(返回是否匹配成功)
boolean flag = Pattern.matcher("正则表达式", "需要进行匹配的字符串");
}
//替换字符串
public void fun3(){
Pattern p = Pattern.compile("正则表达式");
Matcher m = p.matcher("需要处理的字符串");
m.replaceAll("替换的目标字符");
}
//查找符合的字符
public void fun4(){
Pattern p = Pattern.compile("正则表达式");
Matcher m = p.matcher("需要处理的字符串");
boolean flag = m.find();
}
//拆分字符串
public void fun5(){
//以空格拆分字符串
String[] list = "this is my first regex".split("\s");

//计算器
String str2 = "a+b*c-e/f%g";
//根据 +、-、*、/、%、(、)来拆分
String list2 = str2.split("\+|\-|\*|/|%|\(|\)");

}