在 Java 中,使用 正则表达式匹配 String 通常有以下几种常见方式。下面从基础到常用场景给你说明。
String.matches()适合整串完全匹配。
String s = "abc123";
boolean match = s.matches("[a-z]+\\d+");
System.out.println(match); // true
⚠️ 注意:
matches() 是全文匹配,相当于自动加了 ^...$Pattern + Matcherimport java.util.regex.*;
String s = "hello 123 world";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println("包含数字");
}
✅ find():查找是否包含
✅ matches():整体匹配
✅ lookingAt():从开头匹配
String s = "订单号:20240101,金额:99.9";
Pattern pattern = Pattern.compile("订单号:(\\d+),金额:([\\d.]+)");
Matcher m = pattern.matcher(s);
if (m.find()) {
String orderId = m.group(1);
String amount = m.group(2);
System.out.println(orderId); // 20240101
System.out.println(amount); // 99.9
}
String s = "a1b2c3";
String result = s.replaceAll("\\d", "#");
System.out.println(result); // a#b#c#
Matcher m = Pattern.compile("\\d+").matcher("a123b456");
String result = m.replaceAll("X");
String s = "a1 b2 c3";
Matcher m = Pattern.compile("\\w\\d").matcher(s);
while (m.find()) {
System.out.println(m.group());
}
"\\d" // 正确
"\d" // 编译错误
✅ 重复使用 Pattern
private static final Pattern P = Pattern.compile("\\d+");
| 需求 | 正则 |
|---|---|
| 手机号 | 1[3-9]\\d{9} |
| 邮箱 | \\w+@\\w+\\.\\w+ |
| 数字 | \\d+ |
| 中文 | [\\u4e00-\u9fa5]+ |
如果你有具体场景(比如校验、提取、替换、流式处理),可以告诉我,我可以直接帮你写完整代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。