正则表达式是处理字符串的强大工具,Java通过java.util.regex包提供了完善的正则表达式支持。本文将详细介绍Java中正则表达式的使用方法。
Java中主要使用两个类处理正则表达式:
String regex = "\\d+"; // 匹配一个或多个数字
String input = "12345";
boolean isMatch = Pattern.matches(regex, input);
System.out.println(isMatch); // 输出true
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher("Hello World");
while(matcher.find()) {
System.out.println("Found: " + matcher.group());
}
| 表达式 | 描述 |
|---|---|
| . | 匹配任意字符 |
| \d | 匹配数字 |
| \w | 匹配字母、数字或下划线 |
| ^ | 匹配字符串开头 |
| $ | 匹配字符串结尾 |
| [abc] | 匹配a、b或c |
| a|b | 匹配a或b |
String emailRegex = "^[\\w-_.+]*[\\w-_.]@(\\w+\\.)+\\w+\\w$";
String email = "test@example.com";
boolean isValid = email.matches(emailRegex);
String html = "内容";
Pattern tagPattern = Pattern.compile("<([a-z]+)>(.*?)\\1>");
Matcher tagMatcher = tagPattern.matcher(html);
if(tagMatcher.find()) {
System.out.println("标签内容: " + tagMatcher.group(2));
}
Pattern.compile()).*)掌握Java正则表达式可以大大提高字符串处理的效率和灵活性,希望本文能帮助你更好地使用这一强大工具。