用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP