用 Java 正則表示式替換所有匹配的內容


一旦你編譯所需正則表示式並透過將輸入字串作為引數傳遞給 matcher() 方法來檢索匹配器物件。

可以使用 Matcher 類的方法 replaceAll(),將輸入字串的所有匹配部分替換為另一個字串。

此方法接受一個字串(替換字串),並將輸入字串中的所有匹配項替換為它,並返回結果。

示例 1

 即時演示

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\t+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("No.of matches: "+count);
      String result = matcher.replaceAll(" ");
      System.out.println("Result: "+result);
   }
}

輸出

Enter input text:
sample text with tab spaces
No.of matches: 4
Result: sample text with tab spaces

同樣,你可以使用 Matcher 類的 replaceFirst() 方法來替換第一個匹配項。

示例 2

 即時演示

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\d";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("No.of matches: "+count);
      String result = matcher.replaceFirst("#");
      System.out.println("Result: "+result);
   }
}

輸出

Enter input text:
test data 1 2 3
No.of matches: 3
Result: test data # 2 3

更新於:13-Jan-2020

1000 多次瀏覽

開啟你的職業生涯

透過完成課程取得認證

立即開始
廣告