如何使用 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

更新時間:2020 年 1 月 10 日

2K+ 檢視次數

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.