正则表达式是Java开发中处理字符串的强大工具,本文将详细介绍Java正则表达式的编写方法、核心语法和实际应用场景。
Java通过java.util.regex包提供正则表达式支持,主要包含Pattern和Matcher两个类:
// 基本使用示例
Pattern pattern = Pattern.compile("正则表达式");
Matcher matcher = pattern.matcher("待匹配字符串");
boolean isMatch = matcher.matches();
. 匹配任意单个字符\d 匹配数字,等价于[0-9]\w 匹配单词字符[a-zA-Z0-9_]\s 匹配空白字符^ 匹配字符串开头$ 匹配字符串结尾| 量词 | 说明 |
|---|---|
| * | 0次或多次 |
| + | 1次或多次 |
| ? | 0次或1次 |
| {n} | 恰好n次 |
| {n,} | 至少n次 |
| {n,m} | 至少n次,最多m次 |
String regex = "^1[3-9]\\d{9}$";
String phone = "13800138000";
boolean isValid = phone.matches(regex);
String html = "<a href=\"https://example.com\">链接</a>";
Pattern pattern = Pattern.compile("href=\\\"([^\\\"]*)\\\"");
Matcher matcher = pattern.matcher(html);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
String text = "订单号:12345,金额:100元";
String result = text.replaceAll("\\d+", "***");
// 输出:订单号:***,金额:***元
\\dPattern.CASE_INSENSITIVE标志实现不区分大小写匹配Pattern对象提高性能掌握Java正则表达式可以极大提高字符串处理效率,建议多加练习各种常见模式。