English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String replaceAll() method replaces each substring that matches the regular expression in 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 in which 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 representing a sequence of numbers String regex = "\\d+"; //All occurrences of "aa" are replaced 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 substrings 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 = "\\+"; // 대체+" 를 "#"로 대체"를 사용하여 replaceAll() 메서드 ////replaceAll()를 사용하여 “ +”대체”를 “#”로 System.out.println(str1.replaceAll("\\+"", "#")); // #a-#b // 대체+" 를 "#" 로 replace()를 사용하여 대체" System.out.println(str1.replace("+"", "#")); // #a-#b } }
처음에 보았던 것처럼, replace() 메서드를 사용할 때는 특수 문자를 인코딩할 필요가 없습니다. 더 많은 정보를 얻으려면 다음을 방문하세요:Java String replace()
만약 첫 번째 일치하는 부분 문자열만을 대체하려면, 다음을 사용하세요:Java String replaceFirst()메서드。