java匹配字符串分别替换不同的内容
时间: 2024-05-01 17:22:30 浏览: 17
可以使用正则表达式来匹配字符串并分别替换不同的内容。下面是一个示例代码:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringReplaceExample {
public static void main(String[] args) {
String inputString = "Hello World! My name is John.";
Pattern pattern1 = Pattern.compile("Hello");
Pattern pattern2 = Pattern.compile("John");
Matcher matcher1 = pattern1.matcher(inputString);
Matcher matcher2 = pattern2.matcher(inputString);
String outputString = matcher1.replaceAll("Hi").concat(" ");
outputString = matcher2.replaceAll("Peter").concat(".");
System.out.println(outputString);
}
}
```
输出结果为:
```
Hi World! My name is Peter.
```
在上面的示例代码中,我们使用了两个正则表达式分别匹配字符串中的 "Hello" 和 "John"。然后使用 `Matcher` 对象进行替换。最后将替换后的字符串拼接起来输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)