Below snippet remove all the strings that matches to any of the regular expressions.
Find the below working application.
RemoveMatchedStrings.java
package com.sample.app.strings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
public class RemoveMatchedStrings {
public static void removeMatchedStrings(Collection<String> values, Collection<String> patterns) {
if (values == null || values.isEmpty()) {
return;
}
if (patterns == null || patterns.isEmpty()) {
return;
}
List<String> matchedStrings = new ArrayList<String>();
for (String patternToMatch : patterns) {
Pattern pattern = Pattern.compile(patternToMatch);
for (String value : values) {
if (pattern.matcher(value).matches()) {
matchedStrings.add(value);
}
}
}
values.removeAll(matchedStrings);
}
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
strings.add("aab");
strings.add("xyz");
strings.add("ab");
strings.add("fg");
strings.add("de");
List<String> patterns = Arrays.asList("a*b", "d*e");
removeMatchedStrings(strings, patterns);
System.out.println(strings);
}
}
Previous Next Home
No comments:
Post a Comment