當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java String 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)

參數

regex:正則表達式

replacement:替換字符序列

返回

替換字符串

Java String 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 String 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.

點擊我了解正則表達式





相關用法


注:本文由純淨天空篩選整理自 Java String replaceAll()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。