Java中Matcher replaceAll()方法,附示例 p>
java.util.regex.Matcher 類表示用於執行各種匹配操作的引擎。該類沒有建構函式,你可以使用 java.util.regex.Pattern 類的 matches() 方法建立/獲取此類的物件。
此 (Matcher) 類的方法 replaceAll() 接受一個字串值,用給定的字串值替換輸入中所有匹配的子序列並返回結果。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[#%&*]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//Retrieving Pattern used
System.out.println("The are "+count+" special characters [# % & *] in the given text");
//Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
}
}輸出
Enter input text: Hello# How # are# you *& welcome to T#utorials%point The are 7 special characters [# % & *] in the given text Replaced all special characters [# % & *] with !: Hello! How ! are! you !! welcome to T!utorials!point
示例 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match spaces (one or more)
String regex = "\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}輸出
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces
廣告
資料結構 p>
網路 p>
RDBMS p>
作業系統 p>
Java p>
iOS p>
HTML p>
CSS p>
Android p>
Python p>
C程式設計 p>
C++ p>
C# p>
MongoDB p>
MySQL p>
Javascript p>
PHP p>