JUnit
@Test
@BeforeEach
@AfterEach
@BeforeAll
@AfterAll
@Disabled
- …
- 传送门
正则表达式
boolean str.matchs(String regex)
- 正则字符串不同于普通字符串, 特殊字符需要转义, 用普通字符串表示时就需要再次转义
匹配规则
.
任意字符(默认不含换行符\n)\d
数字\w
字母, 数字, 下划线\s
空白字符\D
等同[^\d]
, 非数字\W
等同[^\w]
\S
等同[^\s]
*
任意数量>=0+
一个或多个>=1?
0/1{n}
n个字符{n,m}
n~m个字符(书写不能留空格){n,}
>=n个字符(书写不能留空格)
复杂规则
^$
匹配开头和结尾[0-9a-zA-Z]
匹配指定范围[^...]
排除范围|
或规则匹配()
括号表示一组或范围, 可以结合|
使用, 对于单字符的|
, 等效字符的[]
分组匹配
-
java.util.regex.*
-
String.matches()
不变获取分组内容, 使用Pattern
对象匹配Matcher
对象``Matcher.group(index)` -
分组匹配:
Pattern p = Pattern.compile("(\\d{3,4})\\-(\\d{7,8})"); // 编译正则表达式 Matcher m = p.matcher("010-12345678"); // 匹配成功返回Matcher对象, 否则空Matcher对象 m.matches(); // 判断是否匹配true/false, 成功后才能调用group String m0 = m.group(0); // 返回整个匹配的字符串 String mn = m.group(n); // 返回第n个分组的字符串内容
非贪婪匹配
- 正则表达式的数量修饰符默认是贪婪匹配, 即尽可能多的匹配
- 在数量修饰符后面加上
?
即可使用非贪婪匹配规则, 是一种弹性匹配规则
搜索和替换
分割字符串
String.split()
方法可以传入正则表达式:
"a b c".split("\\s"); // { "a", "b", "c" }
"a b c".split("\\s"); // { "a", "b", "", "c" }
"a, b ;; c".split("[\\,\\;\\s]+"); // { "a", "b", "c" }
搜索
Matcher.find()
可以在整串中查找匹配串
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String s = "the quick brown fox jumps over the lazy dog.";
Pattern p = Pattern.compile("\\wo\\w");
Matcher m = p.matcher(s);
while (m.find()) {
String sub = s.substring(m.start(), m.end());
System.out.println(sub);
}
}
}
替换
String.replaceAll(regex, repl)
方法可以传入正则表达式替换
public class Main {
public static void main(String[] args) {
String s = "The quick\t\t brown fox jumps over the lazy dog.";
String r = s.replaceAll("\\s+", " ");
System.out.println(r); // "The quick brown fox jumps over the lazy dog."
}
}
反向引用
在使用String.replaceAll
时, 可以使用$1
, $2
来反向引用正则表达式匹配的分组, 从而可以进行更复杂的替换操作
String.replaceAll
内部直接调用的是Matcher.replaceAll