正则表达式(Regular Expression)是一种强大的文本处理工具,Java通过java.util.regex包提供完整的正则表达式支持。
Pattern类表示编译后的正则表达式:
Pattern pattern = Pattern.compile("\\d+"); // 匹配数字
Matcher类用于对字符串进行匹配操作:
Matcher matcher = pattern.matcher("123abc");
boolean isMatch = matcher.find(); // 返回true
String emailRegex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
boolean isValid = Pattern.matches(emailRegex, "test@example.com");
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("价格: 99元");
while(m.find()) {
System.out.println(m.group()); // 输出99
}