I want to add regex to one of my projects which allows for multiple patterns and matchers.
I currently have an enum that stores types:
public enum Types {
OAK_DOOR,
BIRCH_DOOR,
BAMBOO_DOOR,
CAKE,
RANDOM,
WHITE_BED,
RED_BED,
PINK_BED,
BLACK_BED;
}
Here is my current code:
public Set<String> getTypes() {
Set<String> foundTypes = Sets.newHashSet();
List<String> regexPatterns = Lists.newArrayList("^.*?_BED", "^.*?_DOOR");
for (String regexPattern : regexPatterns) {
Pattern pattern = Pattern.compile(regexPattern);
for (Types type : Types.values()) {
String name = type.name();
Matcher m = pattern.matcher(name);
while (m.find()) {
foundTypes.add(m.group());
}
}
}
return foundTypes;
}
This is not returning any values from the Types enum.
What am I doing wrong?
1
If you want to match types ending in either DOOR
or BED
, then just use a single regex pattern:
_(?:DOOR|BED)$
Updated Java code:
public Set<String> getTypes() {
Set<String> foundTypes = Sets.newHashSet();
String regexPattern = "_(?:DOOR|BED)$";
Pattern pattern = Pattern.compile(regexPattern);
for (Types type : Types.values()) {
String name = type.name();
Matcher m = pattern.matcher(name);
if (m.find()) {
foundTypes.add(m.group());
}
}
return foundTypes;
}
Your Code List regexPatterns is not initiated properly with java sdk.
The following changes work smoothly:
List<String> regexPatterns = new ArrayList<>(Arrays.asList("^.*?_BED", "^.*?_DOOR"));
3