如何使用 Java 中的正則表示式列印字串中的所有字元?
元字元“.”匹配所有字元,使用正則表示式列印所有字元,如下所示:-
使用 compile() 方法編譯正則表示式。
使用 matcher() 方法建立一個 Matcher 物件。
使用 find() 方法查詢匹配項,併為每個匹配項使用 group() 方法列印匹配的內容(字元)。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
//Regular expression to match a string of non-word with length 2 to 6
String regex = ".";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your input string: ");
String input = sc.nextLine();
//Creating a Pattern object
Pattern p = Pattern.compile(regex);
//Creating a Matcher object
Matcher m = p.matcher(input);
while(m.find()) {
System.out.println(m.group());
}
}
}輸出
Enter your input string: This is a sample text T h i s i s a s a m p l e t e x t
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP