So I have a string that looks something like this:
text java.awt.Color[r=128,g=128,b=128]text 1234
How could I pop out the color and get the rgb values?
CodePudding user response:
You can get the rgb values from that string with this:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
String[] colorValues = new String[3];
int index = 0;
for (String string : temp) {
try {
Integer.parseInt(string);
colorValues[index] = string;
index ;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
The above example extract the values in an array of Strings, if you want in an array of ints:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
int[] colorValues = new int[3];
int index = 0;
for (String string : temp) {
try {
colorValues[index] = Integer.parseInt(string);
index ;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
CodePudding user response:
As said before, you will need to parse the text. This will allow you to return the RGB values from inside the string. I would try something like this.
private static int[] getColourVals(String s){
int[] vals = new int[3];
String[] annotatedVals = s.split("\\[|\\]")[1].split(","); // Split the string on either [ or ] and then split the middle element by ,
for(int i = 0; i < annotatedVals.length; i ){
vals[i] = Integer.parseInt(annotatedVals[i].split("=")[1]); // Split by the = and only get the value
}
return vals;
}