Java字符串replaceAll()

本文概述

  • Java字符串replaceAll()示例:替换字符
  • 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.

点击我了解正则表达式

    推荐阅读