正则表达式(Regular Expression)是一种强大的文本处理工具,Java通过java.util.regex包提供完整的正则支持。
用于编译正则表达式:
Pattern pattern = Pattern.compile("\\d+");
执行匹配操作:
Matcher matcher = pattern.matcher("123abc");
boolean isMatch = matcher.find();
String emailRegex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
String phoneRegex = "^1[3-9]\\d{9}$";
String result = "a1b2c3".replaceAll("\\d", "X");
通过掌握这些Java正则表达式用法,可以显著提升文本处理效率和代码质量。