Java中的 Matcher replaceFirst( 函数 ) 方法及示例
Matcher 类的replaceFirst( 函数)方法表现为追加和替换方法。此方法将匹配器中匹配的模式的第一个实例替换为参数中传递的函数。
句法:
public String replaceFirst(
Function replacerFunction)
参数:这个方法接受一个参数replacerFunction ,它是定义匹配器替换的函数。
返回值:该方法返回一个字符串,其目标字符串是通过替换字符串构造的。
异常:此方法引发以下异常:
- NullPointerException : 如果替换函数为空
- ConcurrentModificationException : 如果检测到替换函数修改了这个匹配器的状态
下面的示例说明了 Matcher.replaceFirst() 方法:
示例 1:
// Java code to illustrate replaceFirst() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "(Geeks)";
// Create a pattern from regex
Pattern pattern
= Pattern.compile(regex);
// Get the String to be matched
String stringToBeMatched
= "GeeksForGeeks Geeks for For Geeks Geek";
// Create a matcher for the input String
Matcher matcher
= pattern.matcher(stringToBeMatched);
System.out.println("Before Replacement: "
+ stringToBeMatched);
// Get the String to be replaced
String stringToBeReplaced = "Geeks";
StringBuilder builder
= new StringBuilder();
// Replace every matched pattern
// with the target String
// using replaceFirst() method
System.out.println("After Replacement: "
+ matcher
.replaceFirst(
x -> x.group().toUpperCase()));
}
}
输出:
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek
After Replacement: GEEKSForGeeks Geeks for For Geeks Geek
示例 2:
// Java code to illustrate replaceFirst() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "(FGF)";
// Create a pattern from regex
Pattern pattern
= Pattern.compile(regex);
// Get the String to be matched
String stringToBeMatched
= "GFG FGF GFG GFG FGF";
// Create a matcher for the input String
Matcher matcher
= pattern.matcher(stringToBeMatched);
System.out.println("Before Replacement: "
+ stringToBeMatched);
// Get the String to be replaced
String stringToBeReplaced = "(GFG)";
StringBuilder builder
= new StringBuilder();
// Replace every matched pattern
// with the target String
// using replaceFirst() method
System.out.println("After Replacement: "
+ matcher
.replaceFirst(
x -> x.group().toLowerCase()));
}
}
输出:
Before Replacement: GFG FGF GFG GFG FGF
After Replacement: GFG fgf GFG GFG FGF
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/regex/Matcher.html#replaceFirst-java.util。函数。函数-