Java - 由Regex过滤列表条目 [英] Java - Filtering List Entries by Regex

查看:71
本文介绍了Java - 由Regex过滤列表条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示:

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

它返回一个列表,其中只包含与<$ c $匹配的条目C>正则表达式。
我想知道是否有这样的内置函数:

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:

List<String> filterList(List<String> list, String regex) {
  List<String> result = new ArrayList<String>();
  result.addAll(list, regex);
  return result;
}


推荐答案

Google的Java库(番石榴)有一个接口谓词< T> 这可能对你的情况非常有用。

Google's Java library(Guava) has an interface Predicate<T> which might be pretty useful for your case.

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

要将iterable转换为列表,您可以再次使用Guava:

And to convert the iterable to a list, you can again use Guava:

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

这篇关于Java - 由Regex过滤列表条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆