Return splitted value

160 views Asked by At

I'm having problems in splitting values in java. I have a string, and this must be split using the method .split(), but I need to return this value.

For example I have this string:

[#ff0000]red[#0000ff]blue

Now I need you to return the value FF0000 for the red, and the value 0000FF for blue.

Example:

String str = "[#FF0000]red[#0000FF]blue";
String[] ss = str.split("\\[\\#([0-9a-f]{6})\\]");
for (String s : ss) {
    System.out.println(s);
}

The string is split properly, but do not know how to return the hexadecimal value. Thanks to anyone to help me.

2

There are 2 answers

0
Abhi On BEST ANSWER

How about first split by [ and then split by ]

String str = "[#FF0000]red[#0000FF]blue";
        String[] ss = str.split("\\[");
        String[] sRe = Arrays.copyOfRange(ss, 1, ss.length);

        for (String s : sRe) {
            System.out.println(s.split("\\]")[0]);
            System.out.println(s.split("\\]")[1]);
        }
1
ralfstx On

If you can be sure about your input format, why don't you split at # characters and take the first six characters of every part? Something like

String str = "[#FF0000]red[#0000FF]blue";
String[] ss = str.split("#");
for (String s : ss) {
  if (s.length() >= 6) {
    System.out.println(s.subsstring(0, 6));
  }
}

That's clearly not the most elegant solution, but it's a simple way to achieve what you've asked for using the split method.