Just Another Coder
Just Another Coder

Reputation: 47

Java Converting from String to Enum

I'm pretty new to Java and am not sure how to approach this problem. I have a string which can contain Enums but in String version. For example:

String str = "Hello Color.RED what's up?"

how do I convert Color.RED to an enum in the string above?

Upvotes: 1

Views: 139

Answers (2)

WJS
WJS

Reputation: 40024

Another alternative, is to use String.replaceAll to isolate the color within the string. This removes everything except the color. The \\S+ says one or more non space characters. So it could be anything, including something like @#I@S. You could modify that to fit the constraints of your enum.

String str = "Hello Color.RED what's up?";
    
String colr = str.replaceAll(".*\\bColor\\.(\\S+).*", "$1");
Color color = Color.valueOf(colr);
System.out.println(color);

Upvotes: 0

Andreas
Andreas

Reputation: 159086

You find the text RED, e.g. using a regex, then you call Color.valueOf(name).

Pattern p = Pattern.compile("\\bColor\\.([A-Za-z][A-Za-z0-9_]*)\\b");
Matcher m = p.matcher(str);
if (m.find()) {
    String name = m.group(1);
    Color color = Color.valueOf(name);
    System.out.println(color);
}

Upvotes: 2

Related Questions