1

I want to split the values based on the number of occurrences.

  • If the number of occurrences is 4
    e.g. key = A-B-C-D, the answer should be A,B,C,D

  • If the number of occurrences is more than 4
    e.g. key = A-B-C-D-E-F, the answer should be A-B-C,D,E,F

Please find my attempt below:

String key = "A-B-C-D-E-F";
String[] res = key.split("(?<!^[^_]*)_");
System.out.println(Arrays.toString(res));

My output is A-B,C,D,E,F but my expectation is A-B-C,D,E,F

Similarly the number of occurrences varies based on usage. While splitting, I need to get maximum four values.

Please check and let me know about this.

nhahtdh
  • 54,546
  • 15
  • 119
  • 154
Abdul
  • 782
  • 1
  • 12
  • 29

3 Answers3

2

Use

//String key = "A-B-C-D";       // => [A, B, C, D]
String key = "A-B-C-D-E-F"; // => [A_B, C, D, E, F]
int keep = 3;
String[] res = key.split("-");
if (res.length > 4) {
    String first = String.join("-", Arrays.asList(res).subList(0, keep)); 
    List<String> lst = new ArrayList<>();
    lst.add(first);
    lst.addAll(Arrays.asList(res).subList(keep, res.length));
    res = new String[lst.size()];
    res = lst.toArray(res);
}
System.out.println(Arrays.toString(res));

See the IDEONE demo

Basically, I suggest splitting first, and check how many elements we have. Then, just take as many first elements as we need to keep, and then combine this one with the rest.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
0

You can also try this regex way:

public static void main(String[] args) {
    String input[] = { "A-B-C-D", "A-B-C-D-E-F-E-G", "AAAA-BBB-CCC-DD-EE", "BB-CC-DD-EE" };

    for (String str : input) {
        String output = str.replaceAll("(.*)-([\\w]+?)-([\\w]+?)-([\\w]+?)$", "$1 , $2 , $3 , $4");

        System.out.println("[" + str + "]\t\t\t=> [" + output + "]");
    }
}

OUTPUT:

[A-B-C-D]               => [A , B , C , D]
[A-B-C-D-E-F-E-G]       => [A-B-C-D-E , F , E , G]
[AAAA-BBB-CCC-DD-EE]    => [AAAA-BBB , CCC , DD , EE]
[BB-CC-DD-EE]           => [BB , CC , DD , EE]
Mahendra
  • 1,411
  • 8
  • 14
0

Since you want to have maximum four values after splitting, and you start splitting from the back, you can split by the following regex:

key.split("-(?!([^-]+-){3})");

The regex simply splits by a dash, as long as it can't find 3 dashes ahead. This results in the string being split at the last 3 dashes. Assuming that the input string does not end with dash, the resulting array will have exactly 4 values.

nhahtdh
  • 54,546
  • 15
  • 119
  • 154