如何在 Java 中從 String 提取多個整數?


假設我們的字串中包含整數和字元,如下所示 -

String str = "(29, 12; 29, ) (45, 67; 78, 80)";

現在,我們將使用以下模式提取整數 -

\d

我們已經使用 Pattern 類設定了該模式 -

Matcher matcher = Pattern.compile("\d+").matcher(str);

示例

線上示例

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String[] args) {
      String str = "(29, 12; 29, ) (45, 67; 78, 80)";
      Matcher matcher = Pattern.compile("\d+").matcher(str);
      List<Integer>list = new ArrayList<Integer>();
      while(matcher.find()) {
         list.add(Integer.parseInt(matcher.group()));
      }
      System.out.println("Integers = "+list);
   }
}

輸出

Integers = [29, 12, 29, 45, 67, 78, 80]

更新日期:2019 年 7 月 30 日

738 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.