本文概述
- Java字符串replaceAll()示例:替换字符
- Java字符串replaceAll()示例:替换单词
- Java字符串replaceAll()示例:删除空格
内部实施
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
签名
public String replaceAll(String regex, String replacement)
参量
【Java字符串replaceAll()】正则表达式:正则表达式
替换:字符的替换顺序
退货
替换字符串
Java字符串replaceAll()示例:替换字符让我们看一个替换所有出现的单个字符的示例。
public class ReplaceAllExample1{
public static void main(String args[]){
String s1="srcmini 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字符串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.
点击我了解正则表达式
推荐阅读
- Java字符串split()
- Java字符串replace()
- Java String length()
- Java字符串lastIndexOf()
- Java字符串join()
- Java字符串isEmpty()
- Java字符串getChars()
- Java字符串getBytes()
- 情人节微信红包怎样发?情人节发520微信红包办法_微信