1

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?

5
  • You mean to the enum's value? Commented May 11, 2021 at 18:17
  • Do you want it to say Hello Color.RED or just Hello RED? Also is Color a personal enum, or does it come from java.awt? Commented May 11, 2021 at 18:20
  • I kind of want it to generate a new string which should be something like this "Hello" + Color.RED + "what's up" Commented May 11, 2021 at 18:38
  • To clarify a previous comment, Is Color your enum? Because java.awt.Color is a class not an enum. Commented May 11, 2021 at 21:26
  • @WJS no Color is just an example, my actual Enum is ChatColor Commented May 12, 2021 at 5:42

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

not what I was expecting but works well, thanks
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.