JAVA中正则表达式的入门与使用
一,基础概念
正则表达式(Regex) 用于匹配字符串中的特定模式,Java 中通过 java.util.regex 包实现,核心类为:
Pattern:编译后的正则表达式对象。
Matcher:用于在输入字符串中查找匹配项。
二,如何快速入门
1,编译正则表达式
Pattern pattern = Pattern.compile("你的正则表达式");
2,创建匹配器
Matcher matcher = pattern.matcher("要匹配的字符串");
3,执行匹配
常用方法:
- find():查找下一个匹配项。
- matches():检查整个字符串是否匹配。
- group():获取匹配的子字符串。
三,核心语法
1,基本元字符
元字符 | 含义 | 示例 |
---|---|---|
. | 匹配任意单个字符(换行除外) | “a.c” 匹配 “abc”, “a2c” |
^ | 匹配字符串开头 | “^hello” 匹配 “hello…” |
$ | 匹配字符串结尾 | “world$” 匹配 “…world” |
* | 匹配前面的元素 0次或多次 | “a*” 匹配 “”, “a”, “aaa” |
+ | 匹配前面的元素 1次或多次 | “a+” 匹配 “a”, “aaa” |
? | 匹配前面的元素 0次或1次 | “a?” 匹配 “”, “a” |
[ ] | 匹配字符集中的任意一个字符 | [abc] 匹配 “a”, “b”, “c” |
| | 逻辑或(匹配左侧或右侧) | “cat|dog” 匹配 “cat"或"dog” |
2,量词与分组
- 量词:{n}(n次)、{n,}(至少n次)、{n,m}(n到m次) 示例:“a{2}” 匹配 “aa”。
- 分组:(…) 将子表达式分组,可用于捕获或引用。 示例:“(\d{3})-(\d{4})” 捕获电话号码的区号和号码。
3,预定义字符类
字符类 | 含义 |
---|---|
\d | 匹配数字(0-9) |
\D | 匹配非数字 |
\w | 匹配字母、数字、下划线 |
\W | 匹配非单词字符 |
\s | 匹配空白字符(空格、换行) |
\S | 匹配非空白字符 |
四、场景应用
1,验证邮箱格式
String email = "user@example.com";
Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
Matcher matcher = pattern.matcher(email);
boolean isValid = matcher.matches(); // true 或 false
2,提取电话号码
String text = "电话:138-1234-5678";
Pattern pattern = Pattern.compile("\\d{3}-\\d{4}-\\d{4}");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {System.out.println(matcher.group()); // 输出 "138-1234-5678"
}
3,替换字符串
String text = "价格:$99.99";
Pattern pattern = Pattern.compile("\\$\\d+\\.\\d{2}");
Matcher matcher = pattern.matcher(text);
String replaced = matcher.replaceAll("¥100.00"); // 替换为 ¥100.00
4, 分割字符串
String csv = "apple,banana,cherry";
String[] fruits = csv.split(","); // 输出 ["apple", "banana", "cherry"]
五、正则使用tips
1,转义字符
在 Java 字符串中,反斜杠 \ 需要转义为 \。
示例:正则表达式 \d 在代码中写为 “\d”。
2,性能优化
频繁使用正则时,建议预编译 Pattern 对象:
private static final Pattern EMAIL_PATTERN = Pattern.compile("...");
3,边界匹配
使用 ^ 和 $ 确保匹配整个字符串,而非子串:
例如"^start" 匹配以 “start” 开头的字符串,“end$” 匹配以 “end” 结尾的字符串。
4,分组捕获
使用 () 分组,通过 group(int) 获取子匹配结果:
Pattern pattern = Pattern.compile("(\\d{3})-(\\d{4})");Matcher matcher = pattern.matcher("123-4567");System.out.println(matcher.group(1)); // 输出 "123"