replaceAll()
方法用指定的文本替换与字符串正则表达式匹配的每个子字符串。
示例
class Main { public static void main(String[] args) { String str1 = "Java123is456fun"; // regex for sequence of digits String regex = "\\d+"; // replace all occurrences of numeric // digits by a space System.out.println(str1.replaceAll(regex, " ")); } } // Output: Java is fun
replaceAll() 的语法
replaceAll()
方法的语法是:
string.replaceAll(String regex, String replacement)
这里,
string 是
String
类的对象。
replaceAll() 参数
replaceAll()
方法有两个参数。
replaceAll() 返回值
replaceAll()
方法
示例 1: Java 字符串 replaceAll()
class Main { public static void main(String[] args) { String str1 = "aabbaaac"; String str2 = "Learn223Java55@"; // regex for sequence of digits String regex = "\\d+"; // all occurrences of "aa" is replaceAll with "zz" System.out.println(str1.replaceAll("aa", "zz")); // zzbbzzac // replace a digit or sequence of digits with a whitespace System.out.println(str2.replaceAll(regex, " ")); // Learn Java @ } }
在上面的例子中,
"\\d+"
是一个匹配一个或多个数字的正则表达式。要了解更多信息,请访问 Java 正则表达式。
replaceAll() 中的转义字符
replaceAll()
方法可以将正则表达式或典型字符串作为第一个参数。这是因为典型的字符串本身就是一个正则表达式。
在正则表达式中,有些字符具有特殊含义。这些元字符是:
\ ^ $ . | ? * + {} [] ()
如果您需要匹配包含这些元字符的子字符串,您可以使用
\
或使用
replace()
方法对这些字符进行转义。
// Program to replace the + character class Main { public static void main(String[] args) { String str1 = "+a-+b"; // replace "+" with "#" using replaceAll() // need to escape "+" System.out.println(str1.replaceAll("\\+", "#")); // #a-#b // replace "+" with "#" using replace() System.out.println(str1.replace("+", "#")); // #a-#b } }
如您所见,当我们使用
replace()
方法时,我们不需要转义元字符。要了解更多信息,请访问: Java String replace()
如果您只需要替换匹配子字符串的第一次出现,请使用 Java String replaceFirst() 方法。