是否有一种有效的方法/现有解决方案将字符串"rgb(x,x,x)"[其中x在这种情况下为0-255]解析为颜色对象?[我打算使用颜色值将它们转换为十六进制颜色的方便性.
我更希望有一个GWT选项.我也意识到使用像Scanner.nextInt这样的东西很容易.但是我一直在寻找一种更可靠的方式来获取这些信息.
Con*_*nce 28
据我所知,没有像Java或GWT这样内置的东西.你必须编写自己的方法代码:
public static Color parse(String input)
{
Pattern c = Pattern.compile("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)");
Matcher m = c.matcher(input);
if (m.matches())
{
return new Color(Integer.valueOf(m.group(1)), // r
Integer.valueOf(m.group(2)), // g
Integer.valueOf(m.group(3))); // b
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它
// java.awt.Color[r=128,g=32,b=212]
System.out.println(parse("rgb(128,32,212)"));
// java.awt.Color[r=255,g=0,b=255]
System.out.println(parse("rgb (255, 0, 255)"));
// throws IllegalArgumentException:
// Color parameter outside of expected range: Red Blue
System.out.println(parse("rgb (256, 1, 300)"));
Run Code Online (Sandbox Code Playgroud)
对于那些不了解正则表达式的用户:
public class Test
{
public static void main(String args[]) throws Exception
{
String text = "rgb(255,0,0)";
String[] colors = text.substring(4, text.length() - 1 ).split(",");
Color color = new Color(
Integer.parseInt(colors[0].trim()),
Integer.parseInt(colors[1].trim()),
Integer.parseInt(colors[2].trim())
);
System.out.println( color );
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我知道有人会对错误检查发表评论。我把这个问题留给了海报。通过执行以下操作可以轻松处理:
if (text.startsWith("rgb(") && text.endsWith(")"))
// do the parsing
if (colors.length == 3)
// build and return the color
return null;
Run Code Online (Sandbox Code Playgroud)
关键是你不需要一个乍一看没人理解的复杂的正则表达式。添加错误条件是一项简单的任务。