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()
方法接受两个参数。
- regex - 要替换的正则表达式(可以是普通字符串)
- replacement - 匹配的子字符串将被此字符串替换
replaceAll() 返回值
replaceAll()
方法
- 返回一个新字符串,其中匹配子字符串的每个实例都替换为replacement 字符串。
示例 1:Java String 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+"
是一个匹配一个或多个数字的正则表达式。
在 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() 方法。