📅  最后修改于: 2020-09-26 06:04:47             🧑  作者: Mango
Java 字符串 replaceAll()方法返回一个字符串,该字符串替换与regex和替换字符串匹配的所有字符序列。
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
public String replaceAll(String regex, String replacement)
regex
:正则表达式
replacement
:字符的替换顺序
替换字符串
让我们看一个替换所有出现的单个字符的示例。
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
让我们看一个示例来替换所有出现的单个单词或一组单词。
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.
让我们看一个删除所有出现的空格的示例。
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.