I wonder why none of the other commenters has already mentioned it, but there is an established way to solve this class of problems: Regular Expressions
You described two patterns:
Many deveolpers are afraid of Regular Expressions, but they are extremely helpful here. All you have to do in your code, is to pick the values from the matches:
package color;
import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ColorParser {
private final Pattern namedPattern = Pattern.compile("color\\((\\w+)\\)");
private final Pattern rgbPattern = Pattern.compile("color\\(RGB\\((\\d+)\\,(\\d+)\\,(\\d+)\\)\\)");
public Color parse(String line) {
Color result = parseRGB(line);
if (result == null) {
result = parseNamed(line);
}
return result;
}
private Color parseRGB(String line) {
final Matcher matcher = rgbPattern.matcher(line);
if (matcher.find()) {
final int red = Integer.parseInt(matcher.group(1));
final int green = Integer.parseInt(matcher.group(2));
final int blue = Integer.parseInt(matcher.group(3));
return new Color(red, green, blue);
}
return null;
}
private Color parseNamed(String line) {
final Matcher matcher = namedPattern.matcher(line);
if (matcher.find()) {
final String name = matcher.group(1);
try {
// java.awt.Color is not an enum, so let's use Reflection
return (Color) Color.class.getField(name.toUpperCase()).get(null);
} catch (Exception e) {
// ignore
}
}
return null;
}
}
Here is a JUnit test to verify it:
package color;
import static org.junit.Assert.assertEquals;
import java.awt.Color;
import org.junit.Test;
public class ColorParserTest {
final ColorParser sut = new ColorParser();
@Test
public void testParse_Named() {
assertEquals(Color.BLACK, sut.parse("color(black)"));
}
@Test
public void testParse_NamedInText() {
assertEquals(Color.RED, sut.parse("foo color(Red) bar"));
}
@Test
public void testParse_RGB() {
assertEquals(Color.ORANGE, sut.parse("color(RGB(255,200,0))"));
}
@Test
public void testParse_Unkown() {
assertEquals(null, sut.parse("color(foo)"));
}
}
I used the AWT Color class here. Depending on your use case you might need a mapping table to resolve other named colors, like HTML colors or X11 colors.