java如何使用正则
正则表达式基础语法
正则表达式由普通字符(如字母、数字)和元字符(特殊符号)组成。常用元字符:
\d:匹配数字(等价于[0-9])\w:匹配字母、数字或下划线.:匹配任意单个字符(除换行符)*:匹配前一个字符0次或多次+:匹配前一个字符1次或多次?:匹配前一个字符0次或1次[]:定义字符集合(如[a-z]匹配小写字母)
Java中使用正则的步骤
1. 导入相关包
import java.util.regex.Pattern;
import java.util.regex.Matcher;
2. 编译正则表达式
通过 Pattern.compile() 方法将字符串编译为 Pattern 对象:
Pattern pattern = Pattern.compile("\\d+"); // 匹配一个或多个数字
注意:Java中需对反斜杠转义(如 \d 写作 \\d)。
3. 创建匹配器
使用 Pattern.matcher() 生成 Matcher 对象:
Matcher matcher = pattern.matcher("123abc");
4. 执行匹配操作
matches():整个字符串完全匹配boolean isMatch = matcher.matches(); // false(因字符串包含非数字)find():查找子串匹配while (matcher.find()) { System.out.println("Found: " + matcher.group()); // 输出 "Found: 123" }replaceAll():替换匹配内容String result = "a1b2".replaceAll("\\d", "-"); // 结果为 "a-b-"
常见用例示例
验证邮箱格式
String emailRegex = "^[\\w.-]+@[\\w.-]+\\.[a-z]{2,6}$";
boolean isValid = "user@example.com".matches(emailRegex); // true
提取字符串中的数字
Pattern numPattern = Pattern.compile("\\d+");
Matcher numMatcher = numPattern.matcher("Price: 50, Tax: 5");
while (numMatcher.find()) {
System.out.println(numMatcher.group()); // 输出 50 和 5
}
分割字符串
String[] parts = "a,b,c".split("\\,"); // 结果为 ["a", "b", "c"]
注意事项
- 性能优化:频繁使用的正则表达式应预编译为
Pattern对象。 - 特殊字符需转义:如
\\.匹配点号,\\*匹配星号。 - 贪婪与懒惰匹配:默认贪婪(最长匹配),添加
?转为懒惰(最短匹配)。例如.*?。







