獲取所有匹配的 Java 正則表示式的列表


Java 未提供任何方法來檢索所有匹配項的列表,因此我們需要使用列表並在 while 迴圈內將結果新增到列表中。

示例

 即時演示

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ListOfMatches{
   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);
      ArrayList list = new ArrayList();
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         list.add(matcher.group());
      }
      Iterator it = list.iterator();
      System.out.println("List of matches: ");
      while(it.hasNext()){
         System.out.println(it.next());
      }
   }
}

輸出

Enter input text:
sample 1432 text 53 with 363 numbers
List of matches:
1432
53
363

更新於:2020 年 1 月 13 日

9K + 次瀏覽

開始您的 職業生涯

完成課程以獲得認證

開始
廣告