首页 > 解决方案 > Java 正则表达式匹配到 arraylist

问题描述

我有这个代码:

String line = "There were bear#67 with dog#1323 and cat#5475 in the forest";
String pattern = ".* ([^ ]+)#(\\d{4}).*";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
    System.out.println("Found value: " + m.group(0) );
    System.out.println("Found value: " + m.group(1) );
    System.out.println("Found value: " + m.group(2) );
}  else {
    System.out.println("NO MATCH");
}

它打印

Found value: There were bear#67 with dog#1323 and cat#5475 in the forest
Found value: cat
Found value: 5475

但是我需要将所有匹配项都设为ArrayList

dog#1323, cat#5475

我该怎么做?

标签: javaregex

解决方案


使用StreamAPI,您只需一条语句即可完成。

演示:

import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> list = Pattern.compile("(?<=\\s?)\\p{L}+#\\d{4}")
                                .matcher("There were bear#67 with dog#1323 and cat#5475 in the forest")
                                .results()
                                .map(MatchResult::group)
                                .collect(Collectors.toList());
        
        System.out.println(list);
    }
}

输出:

[dog#1323, cat#5475]

正则表达式的解释:

  1. (?<=\s?)指定可选空格的正向回溯
  2. \p{L}+指定一个或多个 字母
  3. #指定字符,#
  4. \d{4}指定 4 位数字

推荐阅读