java - 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
我该怎么做?
解决方案
使用Stream
API,您只需一条语句即可完成。
演示:
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]
正则表达式的解释:
推荐阅读
- angular - 角材料表 - 错误:找不到列
- python - 在 Python 中延迟评估/延迟评估
- crashlytics - 将 Firebase Crashlytics 与 Prometheus 集成
- ios - '结果类型的值
' 没有成员 '错误' [Alamofire, Swift 5] - amazon-s3 - S3 批量操作:坚持使用数十亿的 JSON 库存做准备
- angular - 未能对以角度扩展基类的组件运行单元测试
- javascript - WebGL 调用是否保证总订单?
- php - PHP 在一个用户上插入数据库,但不在另一个具有相同权限的用户上
- regex - 改进有效的正则表达式
- kubernetes - Kubernetes 网络策略出口端口