📜  Java字符串之-replaceAll()

📅  最后修改于: 2020-09-26 06:04:47             🧑  作者: Mango

Java字符串replaceAll()

Java 字符串 replaceAll()方法返回一个字符串,该字符串替换与regex和替换字符串匹配的所有字符序列。

内部实现

public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

Signature(签名)

public String replaceAll(String regex, String replacement)

参数

regex:正则表达式

replacement:字符的替换顺序

返回值或类型

替换字符串

Java字符串replaceAll()示例:替换字符

让我们看一个替换所有出现的单个字符的示例。

public class ReplaceAllExample1{
public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"
System.out.println(replaceString);
}}
jevetpoint is e very good website

Java字符串replaceAll()示例:替换单词

让我们看一个示例来替换所有出现的单个单词或一组单词。

public class ReplaceAllExample2{
public static void main(String args[]){
String s1="My name is Khan. My name is Bob. My name is Sonoo.";
String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"
System.out.println(replaceString);
}}
My name was Khan. My name was Bob. My name was Sonoo.

Java String replaceAll()示例:删除空格

让我们看一个删除所有出现的空格的示例。

public class ReplaceAllExample3{
public static void main(String args[]){
String s1="My name is Khan. My name is Bob. My name is Sonoo.";
String replaceString=s1.replaceAll("\\s","");
System.out.println(replaceString);
}}
MynameisKhan.MynameisBob.MynameisSonoo.