[英]regular expression in without loop
How can I rewrite the following expression without using a loop? 如何不使用循环就重写以下表达式?
Pattern pattern = Pattern.compile(filterRegEx);
Matcher regexMatcher = pattern.matcher("(.*)");
for (String word : words) {
if (pattern.matcher(word).matches()) {
foundList.add(word);
}
}
You'll need to use some form of functional programming if you want to avoid using a loop. 如果要避免使用循环,则需要使用某种形式的函数式编程。 Java 8 will have some new features in this area, but right now you can use the
Collections2#filter
(or Iterables#filter
) method from Google Guava; Java 8将在这方面提供一些新功能,但是现在您可以使用Google Guava的
Collections2#filter
(或Iterables#filter
)方法。 it lets you specify a condition (such as pattern.matcher(word).matches()
) and selects the elements in the collection that match. 它使您可以指定条件(例如
pattern.matcher(word).matches()
)并选择集合中匹配的元素。
Note that the object returned "read through" to the original collection, so you'd need to make a copy of them (such as with ArrayList(Collection)
) if you need to keep the filtered list around. 请注意,该对象将“通读”返回到原始集合,因此,如果需要保留过滤后的列表,则需要制作它们的副本(例如
ArrayList(Collection)
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.