user6706828
user6706828

Reputation:

How to get Regex assigned to certain Enum

do any of you happen to know how can I use regex assigned to enum in order to validate if string fits into it?

Upvotes: 1

Views: 9346

Answers (2)

daniu
daniu

Reputation: 15008

You can give the enum a method checking it

public enum RecordField {
    ...;
    // I always keep the Pattern for regexes that don't change
    // to avoid repetetive compilation
    private Pattern pattern;
    RecordField(String regex) {
        pattern = Pattern.compile(regex);
    }
    public boolean isMatch(String toTest) { 
        return pattern.matcher(toTest).matches();
    }
}

and use it like this

RecordField.PKN.isMatch(yourString);

Upvotes: 3

keil
keil

Reputation: 154

You can set the Pattern directly to the enum...

 public enum RecordField {

    ACTION_ID(Pattern.compile("[A-Z0-9]{4}")),
    TYPE(Pattern.compile("0[1|2|4|5]"));

    private Pattern regex;

    RecordField(Pattern s) {
        this.regex = s;
    }

    public Boolean matches(String text){
        return regex.matcher(text).find();
    }

}

Upvotes: 0

Related Questions