Matcher如果您重复使用JDK提供的,基于A 的分离器实现可能非常简单
Spliterators.AbstractSpliterator:
public class MatcherSpliterator extends AbstractSpliterator<String[]>{ private final Matcher m; public MatcherSpliterator(Matcher m) { super(Long.MAX_VALUE, ORDERED | NonNULL | IMMUTABLE); this.m = m; } @Override public boolean tryAdvance(Consumer<? super String[]> action) { if (!m.find()) return false; final String[] groups = new String[m.groupCount()+1]; for (int i = 0; i <= m.groupCount(); i++) groups[i] = m.group(i); action.accept(groups); return true; }}
请注意,分隔符提供 所有 匹配器组,而不仅仅是完整匹配。另请注意,此分离器支持并行性,因为它
AbstractSpliterator实现了分离策略。
通常,您将使用便利流工厂:
public static Stream<String[]> matcherStream(Matcher m) { return StreamSupport.stream(new MatcherSpliterator(m), false);}
这为您简洁地编写各种复杂的面向正则表达式的逻辑提供了强大的基础,例如:
private static final Pattern emailRegex = Pattern.compile("([^,]+?)@([^,]+)");public static void main(String[] args) { final String emails = "kid@gmail.com, stray@yahoo.com, miks@tijuana.com"; System.out.println("User has e-mail accounts on these domains: " + matcherStream(emailRegex.matcher(emails)) .map(gs->gs[2]) .collect(joining(", ")));}
哪些印刷品
User has e-mail accounts on these domains: gmail.com, yahoo.com, tijuana.com
为了完整起见,您的代码将被重写为
Set<String> set = matcherStream(mtr).map(gs->gs[0].toLowerCase()).collect(toSet());
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)