Java - 按正则表达式过滤列表条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24797857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Filtering List Entries by Regex
提问by Benjy Kessler
My code looks like this:
我的代码如下所示:
List<String> filterList(List<String> list, String regex) {
List<String> result = new ArrayList<String>();
for (String entry : list) {
if (entry.matches(regex)) {
result.add(entry);
}
}
return result;
}
It returns a list that contains only those entries that match the regex
.
I was wondering if there was a built in function for this along the lines of:
它返回一个列表,其中仅包含与regex
. 我想知道是否有这样的内置函数:
List<String> filterList(List<String> list, String regex) {
List<String> result = new ArrayList<String>();
result.addAll(list, regex);
return result;
}
采纳答案by scheffield
In addition to the answer from Konstantin: Java 8 added Predicate
support to the Pattern
class via asPredicate
, which calls Matcher.find()
internally:
除了来自 Konstantin 的回答:Java 8通过内部调用添加Predicate
了对Pattern
类的支持:asPredicate
Matcher.find()
Pattern pattern = Pattern.compile("...");
List<String> matching = list.stream()
.filter(pattern.asPredicate())
.collect(Collectors.toList());
Pretty awesome!
非常棒!
回答by Konstantin V. Salikhov
In java 8 you can do something like this using new stream API:
在 java 8 中,你可以使用新的流 API做这样的事情:
List<String> filterList(List<String> list, String regex) {
return list.stream().filter(s -> s.matches(regex)).collect(Collectors.toList());
}
回答by Juvanis
Google's Java library(Guava) has an interface Predicate<T>
which might be pretty useful for your case.
Google 的 Java 库(Guava)有一个接口Predicate<T>
,可能对您的情况非常有用。
static String regex = "yourRegex";
Predicate<String> matchesWithRegex = new Predicate<String>() {
@Override
public boolean apply(String str) {
return str.matches(regex);
}
};
You define a predicate like the one above and then filter your list based on this predicate with a single-line code:
您可以像上面那样定义一个谓词,然后使用单行代码根据此谓词过滤您的列表:
Iterable<String> iterable = Iterables.filter(originalList, matchesWithRegex);
And to convert the iterable to a list, you can again use Guava:
要将可迭代对象转换为列表,您可以再次使用 Guava:
ArrayList<String> resultList = Lists.newArrayList(iterable);