Search code examples
javaandroidregexenumscheckstyle

Regex to search for lower-case Enum constants


I'm trying to use a regex to parse enums that are lower case, for example:

 enum TransparencyState {
        Gone, Translucent, Opaque
    }

or

 enum TransparencyState {
        gone, 
        translucent, 
        opaque
    }

However, the closest I can get is (?:enum\s+[a-zA-Z0-9]+\s*\{|\G)\s+([a-zA-Z0-9_,\s]*)(?=[^{}]*\}), but that doesn't exactly work. Ideally, it would only match the lower-case constants in a list of enums, anything except all upper-case (essentially in constant form like below).

It would not match:

 enum TransparencyState {
        GONE, TRANSLUCENT, OPAQUE_OR_DULL
    }

Solution

  • Try this regex:

    ^enum[^{]*{\s*(?!\b[A-Z]+\b)(\w+(?:\s*,\s*(?!\b[A-Z]+\b)\w+)*)\s*}
    

    Click for Demo

    In JAVA, escape each \ with another \

    Explanation:

    • ^ - asserts the start of the line
    • enum[^{]*{\s* - matches enum followed by 0+ occurrences of any character that is not a { followed by a { followed by 0+ whitespaces, as many as possible
    • (?!\b[A-Z]+\b) - negative lookahead to make sure that the next word(enum value) does not contain ONLY captial letters
    • \w+ - matches 1+ occurrences of word letters(only if the above negative lookahead condition is true)
    • (?:\s*,\s*(?!\b[A-Z]+\b)\w+)* - matches 0+ other such enum values
    • \s*} - matches 0+ whitespaces followed by a }