以下是一些 Java 中使用正则表达式的基本操作:
1. 匹配字符串:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String input = "The quick brown fox jumps over the lazy dog";
String pattern = "fox";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(input);
if (matcher.find()) {
System.out.println("Pattern found");
} else {
System.out.println("Pattern not found");
}
2. 查找所有匹配:
String input = "The quick brown fox jumps over the lazy dog. The fox is very clever.";
String pattern = "fox";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(input);
while (matcher.find()) {
System.out.println("Pattern found at index: " + matcher.start());
}
3. 替换匹配:
String input = "The quick brown fox jumps over the lazy dog";
String pattern = "fox";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(input);
String replacedString = matcher.replaceAll("cat");
System.out.println("Replaced String: " + replacedString);
4. 分割字符串:
String input = "apple,orange,banana,grape";
String pattern = ",";
Pattern compiledPattern = Pattern.compile(pattern);
String[] parts = compiledPattern.split(input);
for (String part : parts) {
System.out.println(part);
}
5. 正则表达式字符类:
// 匹配任意数字
String pattern = "\\d";
// 匹配字母和数字
String pattern = "[a-zA-Z0-9]";
// 匹配非字母和非数字
String pattern = "[^a-zA-Z0-9]";
6. 正则表达式量词:
// 匹配一个或多个数字
String pattern = "\\d+";
// 匹配零个或多个字母
String pattern = "[a-zA-Z]*";
// 匹配零个或一个字母
String pattern = "[a-zA-Z]?";
7. 使用预定义字符类:
// 匹配任意数字字符
String pattern = "\\d";
// 匹配任意非数字字符
String pattern = "\\D";
// 匹配任意空白字符
String pattern = "\\s";
// 匹配任意非空白字符
String pattern = "\\S";
// 匹配任意字母数字字符
String pattern = "\\w";
// 匹配任意非字母数字字符
String pattern = "\\W";
这只是正则表达式的一小部分功能,正则表达式的语法和功能非常强大,可以满足复杂的模式匹配需求。
转载请注明出处:http://www.zyzy.cn/article/detail/418/Java