📜  Java中的 Matcher replaceAll(String) 方法和示例

📅  最后修改于: 2022-05-13 01:54:43.353000             🧑  作者: Mango

Java中的 Matcher replaceAll(String) 方法和示例

Matcher 类replaceAll(String)方法表现为追加和替换方法。此方法读取输入字符串并将其替换为匹配器字符串中的匹配模式。

句法:

public String replaceAll(String stringToBeReplaced)

参数:此方法接受一个参数stringToBeReplaced ,它是匹配器中要替换的字符串。

返回值:该方法返回一个字符串,其目标字符串是通过替换字符串构造的。

下面的示例说明了 Matcher.replaceAll() 方法:

示例 1:

// Java code to illustrate replaceAll() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(Geeks)";
  
        // Create a pattern from regex
        Pattern pattern = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "GeeksForGeeks Geeks for For Geeks Geek";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(stringToBeMatched);
  
        System.out.println("Before Replacement: "
                           + stringToBeMatched);
  
        // Get the String to be replaced
        String stringToBeReplaced = "GFG";
        StringBuilder builder
            = new StringBuilder();
  
        // Replace every matched pattern
        // with the target String
        // using replaceAll() method
        System.out.println("After Replacement: "
                           + matcher
                                 .replaceAll(stringToBeReplaced));
    }
}
输出:
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek
After Replacement: GFGForGFG GFG for For GFG Geek

示例 2:

// Java code to illustrate replaceAll() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(FGF)";
  
        // Create a pattern from regex
        Pattern pattern = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(stringToBeMatched);
  
        // Get the String to be replaced
        String stringToBeReplaced = "GFG";
        StringBuilder builder
            = new StringBuilder();
  
        // Replace every matched pattern
        // with the target String
        // using replaceAll() method
        System.out.println("After Replacement: "
                           + matcher
                                 .replaceAll(stringToBeReplaced));
    }
}
输出:
After Replacement: GGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/regex/Matcher.html#replaceAll-java.lang.String-