获取所有匹配项的 Java 正则表达式列表
javaobject oriented programmingprogramming更新于 2025/2/13 15:40:17
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+";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
ArrayList list = new ArrayList();
//匹配字符串中的编译模式
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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

