Java中常用的正则表达式函数介绍
正则表达式是一种字符串匹配模式,它使开发人员能够在处理文本时进行高效的搜索、替换和验证操作。Java提供了许多正则表达式相关的函数和类,这些函数和类可以在处理字符串时,非常方便地使用正则表达式。
1. String.replaceAll(String regex, String replacement)
该函数用于将指定字符串中匹配正则表达式的所有子串替换为指定的字符串。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
String replacedStr = str.replaceAll("fox", "cat");
// 输出结果
// The quick brown cat jumps over the lazy dog.
2. String.matches(String regex)
该函数用于测试字符串是否匹配正则表达式。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
boolean matched = str.matches(".*fox.*");
// 输出结果
// true
3. Pattern.compile(String regex)
该函数用于将正则表达式编译成模式。Pattern是一个正则表达式的类,它包含了一些静态方法和常量,比如compile()、matcher()等。
示例代码:
String regex = "[a-z]+";
Pattern pattern = Pattern.compile(regex);
4. Matcher.matches()
该函数用于测试当前匹配器的输入序列是否与给定的正则表达式匹配。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
String regex = ".*[a-zA-Z]{4}.*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
boolean matched = matcher.matches();
// 输出结果
// true
5. Matcher.find()
该函数用于扫描输入序列以查找与给定模式匹配的下一个子序列。此方法返回布尔值,指示是否找到了匹配项。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
String regex = "\\b[a-z]{3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出结果
// The
// fox
// the
// dog
6. Matcher.group()
该函数用于返回与前一个匹配所匹配的子序列。该函数一般结合find函数使用,在每次找到匹配后调用该函数才有效。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
String regex = "\\b[a-z]{3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出结果
// The
// fox
// the
// dog
7. Matcher.replaceFirst()
该函数用于将匹配的 个子序列替换为指定字符串,并返回结果字符串。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
String regex = "\\b[a-z]{3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
String replacedStr = matcher.replaceFirst("cat");
// 输出结果
// The quick brown cat jumps over the lazy dog.
8. Matcher.replaceAll()
该函数用于将匹配的所有子序列都替换为指定字符串,并返回结果字符串。
示例代码:
String str = "The quick brown fox jumps over the lazy dog.";
String regex = "\\b[a-z]{3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
String replacedStr = matcher.replaceAll("cat");
// 输出结果
// The quick brown cat jumps over cat lazy cat.
