温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java String 如何正则匹配

发布时间:2026-10-05 22:25:23 来源:亿速云 阅读:102 作者:小樊 栏目:编程语言

在 Java 中,使用 正则表达式匹配 String 通常有以下几种常见方式。下面从基础到常用场景给你说明。


一、最基础:使用 String.matches()

适合整串完全匹配。

String s = "abc123";
boolean match = s.matches("[a-z]+\\d+");
System.out.println(match); // true

⚠️ 注意:

  • matches() 是全文匹配,相当于自动加了 ^...$
  • 不适合“是否包含某模式”

二、判断是否包含(推荐):Pattern + Matcher

import 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
}

四、替换字符串

1️⃣ String 自带方法

String s = "a1b2c3";
String result = s.replaceAll("\\d", "#");
System.out.println(result); // a#b#c#

2️⃣ Matcher 替换

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());
}

六、常见注意事项 ⚠️

1️⃣ 反斜杠要写两个

"\\d"   // 正确
"\d"    // 编译错误

2️⃣ 性能建议

✅ 重复使用 Pattern

private static final Pattern P = Pattern.compile("\\d+");

七、常用正则示例

需求 正则
手机号 1[3-9]\\d{9}
邮箱 \\w+@\\w+\\.\\w+
数字 \\d+
中文 [\\u4e00-\u9fa5]+

如果你有具体场景(比如校验、提取、替换、流式处理),可以告诉我,我可以直接帮你写完整代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手