English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String replaceAll() method replaces each substring that matches the regular expression of the string with the specified text.
The syntax of the replaceAll() method is:
string.replaceAll(String regex, String replacement)
The replaceAll() method has two parameters.
regex - The regular expression to be replaced (can be a typical string)
replacement - The matched substring is replaced by this string
The replaceAll() method returns a new string where each occurrence of the matched substring is replaced by the replacement string (replacement).
class Main { public static void main(String[] args) { String str1 = "aabbaaac"; String str2 = "Learn223Java55@"; // Regular expression to represent a number sequence String regex = \\\d+"; // Replace all occurrences of "aa" with "zz" System.out.println(str1.replaceAll("aa", "zz")); // zzbbzzac // Replace numbers or number sequences with spaces System.out.println(str2.replaceAll(regex, " ")); // Learn Java @ } }
In the above example, \\\d+" is a regular expression that matches one or more numbers.
The replaceAll() method can take a regular expression or a typical string as the first parameter. This is because a typical string itself is a regular expression.
In regular expressions, some characters have special meanings. These meta-characters are:
\ ^ $ . | ? * + {} [] ()
If you need to match a substring containing these meta-characters, you can use \ or use the replace() method to escape these characters.
// Program to replace the + character class Main { public static void main(String[] args) { String str1 = "+a-+b"; String str2 = "Learn223Java55@"; String regex = "\\+"; // Sostituisci "+" con "#" utilizzando il metodo replaceAll() //// Usa replaceAll() per sostituire "+" con "#" System.out.println(str1.replaceAll("\\+", "#")); // #a-#b // Sostituisci "+" con "#" utilizzando replace() System.out.println(str1.replace("+", "#")); // #a-#b } }
Come vedete, quando si utilizza il metodo replace(), non è necessario eseguire l'escape dei caratteri di riserva. Per ulteriori informazioni, visitare:Java String replace()
Se si desidera sostituire solo il primo match della sottostringa corrispondente, utilizzareJava String replaceFirst()Metodo.