Java-按正则表达式筛选列表项

Java-按正则表达式筛选列表项,java,regex,collections,Java,Regex,Collections,我的代码如下所示: 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 re

我的代码如下所示:

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;
}

在java 8中,您可以使用新的:

列表过滤器列表(列表,字符串正则表达式){
return list.stream().filter(s->s.matches(regex)).collect(Collectors.toList());
}
谷歌的Java库(Guava)有一个接口
谓词
,它可能对您的案例非常有用

static String regex = "yourRegex";

Predicate<String> matchesWithRegex = new Predicate<String>() {
        @Override 
        public boolean apply(String str) {
            return str.matches(regex);
        }               
};
静态字符串regex=“yourRegex”; 谓词matchesWithRegex=新谓词(){ @凌驾 公共布尔应用(字符串str){ 返回str.matches(regex); } }; 您可以定义一个类似于上述谓词的谓词,然后使用单行代码根据该谓词筛选列表:

Iterable<String> iterable = Iterables.filter(originalList, matchesWithRegex);
Iterable Iterable=Iterables.filter(原始列表,与regex匹配);
要将iterable转换为列表,您可以再次使用番石榴:

ArrayList<String> resultList = Lists.newArrayList(iterable);
arraylistresultlist=Lists.newArrayList(iterable);

除了Konstantin的答案之外:Java 8通过
asPredicate
模式添加了
谓词支持,该类在内部调用
Matcher.find()

Pattern pattern = Pattern.compile("...");

List<String> matching = list.stream()
                            .filter(pattern.asPredicate())
                            .collect(Collectors.toList());
Pattern=Pattern.compile(“…”);
列表匹配=List.stream()
.filter(pattern.asPredicate())
.collect(Collectors.toList());

太棒了

对于<代码>列表
,这是可能的,但请考虑其他类型。如果有一个add all获得谓词对象,那么它应该适用于所有类型。如何将结果列表转换回列表?我必须在循环中逐个添加它们吗?这似乎效率低下。唉,我正在使用Java 7。这就是答案!:-)太好了,谢谢分享。(我自己懒得一路向下滚动来找到你的答案,我不得不艰难地找到关于asPredicate的答案:-)很好。是否可以直接获取匹配组,或者是否需要对收集的
列表中的每个元素应用
匹配器
ArrayList<String> resultList = Lists.newArrayList(iterable);
Pattern pattern = Pattern.compile("...");

List<String> matching = list.stream()
                            .filter(pattern.asPredicate())
                            .collect(Collectors.toList());