0

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?

2
  • You need to parse the text. What have you tried? (Can you post) Commented Jul 18, 2022 at 19:23
  • I havent tried anything yet... im asking because I dont know what to do. Commented Jul 18, 2022 at 19:25

2 Answers 2

1

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

2 Comments

And say for example I have a string with multiple of these java.awt.Color[[r=128,g=128,b=128]. How would I get each one out separately then?
@toadless Is almost the same, just use ArrayList instead, to add all the values there and then split by 3 the elements inside.
0

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

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.