# Java 正则表达式
# 1. 匹配
# 1.1. 部分匹配
String str = "A b C d";
String regex = "[a-z]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
boolean isExist = matcher.find();
# 1.2. 完整匹配
方式一:
String str = "abcd";
String regex = "^abc$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
boolean isExist = matcher.find();
方式二:
String str = "abcd";
String regex = "^abc$";
boolean isExist = Pattern.matches(regex, str);
# 2. 替换
# 2.1. matcher.replaceAll()
String text = "Hello World, hello everyone!";
String regex = "hello";
String replacement = "hi";
// 创建Pattern对象,并指定CASE_INSENSITIVE标志
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
// 替换所有匹配项
String result = matcher.replaceAll(replacement);
System.out.println(result); // 输出: Hi World, hi everyone!
# 2.2. str.replaceAll()
String text = "Hello World, hello everyone!";
String regex = "(?i)hello"; // 使用(?i)使匹配忽略大小写
String replacement = "hi";
String result = text.replaceAll(regex, replacement);
System.out.println(result); // 输出: Hi World, hi everyone!
# 2.3. 替换分组
String str = "2025-09-15";
String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
String result = str.replaceFirst(regex, "$1年$2月$3日");
System.out.println(result); //=> 2025年09月15日
# 3. 断言
对已经匹配的内容进行断言
# 3.1. 后置断言
断言 匹配的内容 后面的内容
@Test
public void testRegex2() {
String regex = "v(?=1)"; // 匹配 v 后面为 1 的 v
Matcher matcher = Pattern.compile(regex).matcher("v1");
if (matcher.find()) {
System.out.println(matcher.group()); // v
}
}
@Test
public void testRegex3() {
String regex = "v(?!1)"; // 匹配 v 后面为 非1 的 v
Matcher matcher = Pattern.compile(regex).matcher("v2");
if (matcher.find()) {
System.out.println(matcher.group()); // v
}
}
# 3.2. 前置断言
断言 匹配的内容 签名的内容
@Test
public void testRegex4() {
String regex = "(?<=1)v"; // 匹配 v 前面为 1 的 v
Matcher matcher = Pattern.compile(regex).matcher("1v");
if (matcher.find()) {
System.out.println(matcher.group()); // v
}
}
@Test
public void testRegex5() {
String regex = "(?<!1)v"; // 匹配 v 前面为 非1 的 v
Matcher matcher = Pattern.compile(regex).matcher("2v");
if (matcher.find()) {
System.out.println(matcher.group()); // v
}
}
# 4. 参考
上一篇: 下一篇:
本章目录