搜尋
首頁Javajava教程Java中的replaceAll()

Java中的replaceAll()

Aug 30, 2024 pm 03:38 PM
java

ReplaceAll() 是String 類別的方法,它替換所有與其參數匹配的字符,所有子字串將被我們作為正則表達式傳遞給該方法的輸入替換,並替換給定的盯著這個方法將回傳我們String 物件。它存在於String類別(java.lang.String)這個套件裡面。在本主題中,我們將學習 Java 中的 ReplaceAll()。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

帶參數的語法

公有字串replaceAll(字串正規表示式,字串替換)

以上是replaceAll()方法的方法簽章。由於String類別提供了java in build方法,因此可以直接在我們的程式碼中使用。它需要兩個參數作為輸入:

  • regex(正規表示式):此輸入用於匹配給定的字串。
  • replacement:這用作我們想要的字串,代替上面匹配的字串。這是我們希望將其視為輸出的新內容或字串。

此方法將始終傳回字串物件。還有一件事,正規表示式也使用一種模式,我們將在下面討論。

結果字串:作為輸出

Java中的replaceAll()方法是如何運作的?

replaceAll 是 String 類別中存在的方法。它需要兩個參數作為輸入,即正規表示式和替換。顧名思義,它用於替換字串的某些部分或整個字串。

此方法會拋出下面提到的異常:

1. PatternSyntaxException

這個異常是java中的未經檢查的異常,只有當我們作為輸入參數傳入方法的正規表示式有錯誤時才會發生。與其他類別一樣,它有一些預先定義或內建方法,可以幫助我們識別問題:

  • public String getMessage():此方法包含異常的描述。
  • public int getIndex():此方法將傳回錯誤的索引。
  • public String getPattern():此方法將為我們提供包含錯誤的正規表示式。
  • public String getDescription():此方法將為我們提供有關錯誤的解密。

2.正規表示式詳細資訊

我們作為字串傳遞到方法參數中的正規表示式,但這個正規表示式是模式類別的編譯實例。它存在於 java.util.regex.Pattern 套件中。

這個正規表示式包含以下內容:

  • 圖案
  • 匹配器

我們還有一個匹配器方法。它符合我們的正規表示式。

  • t:用於選項卡
  • a:用於警報
  • cx:控製字元
  • e:轉義字元
  • n:換行
  • f:換頁

3.可用方法

  • split(CharSequence input):該方法傳回 string[] (字串陣列)並代表我們要分割的輸入。
  • split(CharSequence input, int limit):工作原理相同,但方法也接受一個 limit 參數。
  • 靜態模式編譯(String regex,int flags):此方法採用兩個參數,正規表示式和標誌,並編譯我們的正規表示式。
  • 4) 字串模式()
  • 5) 靜態字串引用(String s)

此模式類別也實作了可序列化介面。

這樣,replaceAll就可以在java中工作了。它在內部使用模式和匹配來編譯正規表示式和其他操作。

Java 中的 ReplaceAll() 範例

下面的範例展示如何使用它來替換單一字元、與正規表示式相符的整個字串、從整個字串中刪除空格以及用特殊字元替換字串。

範例#1

在此範例中,我們將正規表示式作為 (.*)java(.*) 傳遞,以替換從頭到尾子字串為 java 的整個字串。

代碼:

import java.io.*;
public class DemoReg {
public static void main(String args[]) {
String str = new String("Example to show replace in java string.");
System.out.print("Resulted string after replace is  :" );
System.out.println(str.replaceAll("(.*)java(.*)", "replaced"));
}
}

輸出:

Java中的replaceAll()

範例#2

在此範例中,我們用特殊字元取代字串的一部分。這意味著我們可以傳遞任何可以被視為字串的東西。我們也可以傳遞數字。

代碼:

public class DemoReg {
public static void main(String args[]) {
String s1="In this we are going to replace the string with some character. (repeat sequence)";
String str=s1.replaceAll("t*"," ***** ");
System.out.println("Ouptut is ::: ");
System.out.println(str);
}
}

輸出:

Java中的replaceAll()

Example #3

In this java class, we are replacing some part of the string with some other content. Example: “replacement done successfully” this in our case.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Now the demo is for replacing string with some another substring";
String result=str.replaceAll("string"," replacement done successfully");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}

Output:

Java中的replaceAll()

Example #4

In this example, we are trying to remove the spaces which are present in the given string. We have so many keywords with slashes (“\\”) that can be used to perform the given string’s operation.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Now we are going to replace the spaces present in the given string.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("\\s","");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}

Output:

Java中的replaceAll()

Example #5

In this java example, we are replacing the string with a single character only. It means when the given character appears in the string each time, it will be replaced by the method.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Replacing single character from the whole string demo.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("e"," X");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}

Output:

Java中的replaceAll()

We can have anything in the replacement, which is a string. But our regular expression has to be valid; otherwise, it will throw an unchecked exception for error containing regular expression in the replaceAll() method.

Conclusion

Replace method is the string class method of java, which takes two parameters. Any type of regular expression we can pass in it will replace the string for us unless it matches. So the above example will give you an understanding that how we can use this.

以上是Java中的replaceAll()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java平台獨立性:與不同的操作系統的兼容性Java平台獨立性:與不同的操作系統的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什麼功能使Java仍然強大什麼功能使Java仍然強大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

頂級Java功能:開發人員的綜合指南頂級Java功能:開發人員的綜合指南May 13, 2025 am 12:04 AM

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。

Java真的平台獨立嗎? '寫一次,在任何地方運行”如何起作用Java真的平台獨立嗎? '寫一次,在任何地方運行”如何起作用May 13, 2025 am 12:03 AM

javaisnotirelyplatemententedduetojvmvariationsandnativecodinteinteration,butitlargelyupholdsitsitsworapromise.1)javacompilestobytecoderunbythejvm

揭示JVM:您了解Java執行的關鍵揭示JVM:您了解Java執行的關鍵May 13, 2025 am 12:02 AM

thejavavirtualmachine(JVM)IsanabtractComputingmachinecrucialforjavaexecutionasitrunsjavabytecode,使“ writeononce,runanywhere”能力

Java仍然是基於新功能的好語言嗎?Java仍然是基於新功能的好語言嗎?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

是什麼使Java很棒?關鍵特徵和好處是什麼使Java很棒?關鍵特徵和好處May 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

前5個Java功能:示例和解釋前5個Java功能:示例和解釋May 12, 2025 am 12:09 AM

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具