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?
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);
}
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);
Hello Color.REDor justHello RED? Also isColora personal enum, or does it come fromjava.awt?java.awt.Coloris a class not an enum.