Java - Filtering List Entries by Regex
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);
And to convert the iterable to a list, you can again use Guava:
ArrayList<String> resultList = Lists.newArrayList(iterable);
In addition to the answer from Konstantin: Java 8 added Predicate
support to the Pattern
class via asPredicate
, which calls Matcher.find()
internally:
Pattern pattern = Pattern.compile("...");
List<String> matching = list.stream()
.filter(pattern.asPredicate())
.collect(Collectors.toList());
Pretty awesome!
In java 8 you can do something like this using new stream API:
List<String> filterList(List<String> list, String regex) {
return list.stream().filter(s -> s.matches(regex)).collect(Collectors.toList());
}