matcher.replaceFirst
时间: 2023-08-15 14:14:52 浏览: 40
`matcher.replaceFirst()` 是 `java.util.regex.Matcher` 类中的一个方法,用于替换匹配到的第一个子序列。
下面是一个示例代码,演示如何使用 `matcher.replaceFirst()` 方法替换字符串中的匹配项:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "Hello ${name}, welcome to ${city}!";
Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceFirst("John");
System.out.println("Result: " + result);
}
}
```
在上述代码中,我们首先定义了一个输入字符串 `input`,其中包含了两个需要替换的匹配项 `${name}` 和 `${city}`。然后,我们使用正则表达式 `\$\{([^}]+)\}` 创建了一个模式,并使用 `pattern.matcher(input)` 创建了一个匹配器 `matcher`。
接下来,我们使用 `matcher.replaceFirst("John")` 将第一个匹配项替换为 "John"。注意,替换后的结果并不会修改原始字符串 `input`,而是返回一个新的字符串。
最后,我们打印出替换后的结果。
输出结果将会是:
```
Result: Hello John, welcome to ${city}!
```
在这个示例中,我们替换了第一个匹配项 `${name}` 为 "John",而 `${city}` 保持不变。如果想要替换所有匹配项,可以使用 `matcher.replaceAll()` 方法。