如何创建正则表达式匹配项流?
2022-09-01 08:54:30
我正在尝试解析标准输入并提取与特定模式匹配的每个字符串,计算每个匹配项的出现次数,并按字母顺序打印结果。这个问题似乎与 Streams API 很匹配,但我找不到一种简洁的方法来从 Matcher 创建匹配项流。
我通过实现对匹配项的迭代器并将其包装到流中来解决此问题,但结果不是很可读。如何在不引入其他类的情况下创建正则表达式匹配流?
public class PatternCounter
{
static private class MatcherIterator implements Iterator<String> {
private final Matcher matcher;
public MatcherIterator(Matcher matcher) {
this.matcher = matcher;
}
public boolean hasNext() {
return matcher.find();
}
public String next() {
return matcher.group(0);
}
}
static public void main(String[] args) throws Throwable {
Pattern pattern = Pattern.compile("[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)");
new TreeMap<String, Long>(new BufferedReader(new InputStreamReader(System.in))
.lines().map(line -> {
Matcher matcher = pattern.matcher(line);
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(new MatcherIterator(matcher), Spliterator.ORDERED), false);
}).reduce(Stream.empty(), Stream::concat).collect(groupingBy(o -> o, counting()))
).forEach((k, v) -> {
System.out.printf("%s\t%s\n",k,v);
});
}
}