English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

教程基础Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestione eccezioni Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java String replaceAll() usage and example

Metodi Stringa (stringa) Java

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)

replaceAll() parameters

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

replaceAll() return value

  • The replaceAll() method returns a new string where each occurrence of the matched substring is replaced by the replacement string (replacement).

Example 1: Java String replaceAll() method

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.

Escaped characters in replaceAll()

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.

Metodi Stringa (stringa) Java