replaceAll方法
时间: 2023-09-08 09:14:42 浏览: 72
replaceAll是Java String类中的一个方法,它可以替换所有符合特定规则的字符串。具体来说,该方法接受两个参数:第一个参数是一个正则表达式,用于匹配需要替换的字符串;第二个参数是一个替换字符串,用于替换匹配到的字符串。
例如,假设我们有一个字符串"Hello, World!",我们想将其中的逗号替换为句号,可以使用以下代码:
```
String str = "Hello, World!";
str = str.replaceAll(",", ".");
System.out.println(str);
```
运行结果为:"Hello. World!"
相关问题
replaceall方法
`replaceAll` 方法是 Java 中 String 类的一个方法,用于将字符串中的某些子字符串替换为新的字符串。这个方法的语法如下:
```java
public String replaceAll(String regex, String replacement)
```
其中 `regex` 是一个正则表达式,表示要被替换的字符串模式,`replacement` 是一个新的字符串,用于替换匹配的字符串模式。
例如,下面的代码将字符串中所有的空格替换为下划线:
```java
String str = "Hello World";
str = str.replaceAll("\\s", "_");
System.out.println(str); // 输出 "Hello_World"
```
在这里,`\\s` 表示空格字符,因为在正则表达式中空格需要进行转义。注意,`replaceAll` 方法返回一个新的字符串,原始字符串不会被修改。
string replaceAll方法
replaceAll方法是Java中String类的一个方法,用于将字符串中所有匹配某个正则表达式的子串替换成另一个字符串。它的方法签名如下:
```
public String replaceAll(String regex, String replacement)
```
其中,regex表示要匹配的正则表达式,replacement表示要替换成的字符串。
示例:
```java
String str = "hello world";
str = str.replaceAll("l", "L");
System.out.println(str); // 输出:heLLo worLd
```
这个例子中,我们将字符串中所有的小写字母“l”替换成了大写字母“L”。注意,replace方法只会替换第一个匹配到的子串,而replaceAll会替换所有匹配到的子串。
阅读全文
相关推荐














