1. 匹配字符串:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String regex = "pattern";
String input = "input string";
// 创建Pattern对象
Pattern pattern = Pattern.compile(regex);
// 创建Matcher对象
Matcher matcher = pattern.matcher(input);
// 查找匹配
boolean isMatch = matcher.find();
2. 简单匹配:
String regex = "hello";
String input = "Hello, World!";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
boolean isMatch = matcher.find();
3. 匹配多个字符:
// 匹配任意数字
String regex = "\\d+";
// 匹配邮箱地址
String emailRegex = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b";
4. 替换字符串:
String regex = "\\s+"; // 匹配空白字符
String input = " Hello World ";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// 替换匹配的部分
String result = matcher.replaceAll("");
5. 提取匹配的部分:
String regex = "\\d+";
String input = "There are 123 apples and 456 oranges.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// 提取匹配的数字
while (matcher.find()) {
System.out.println("Match: " + matcher.group());
}
6. 正则表达式分组:
String regex = "(\\d+)-(\\d+)";
String input = "Phone numbers: 123-456, 789-012";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// 分组提取
while (matcher.find()) {
String wholeMatch = matcher.group(0);
String group1 = matcher.group(1);
String group2 = matcher.group(2);
System.out.println("Match: " + wholeMatch);
System.out.println("Group 1: " + group1);
System.out.println("Group 2: " + group2);
}
这些是Java中使用正则表达式的基本操作。正则表达式是一个强大的工具,可以用于字符串的匹配、替换和提取等操作。
转载请注明出处:http://www.zyzy.cn/article/detail/13475/Java