Abdul
Abdul

Reputation: 1040

Split the string based on number of occurrences in Java

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

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.

Upvotes: 1

Views: 236

Answers (3)

nhahtdh
nhahtdh

Reputation: 56809

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.

Upvotes: 0

Mahendra
Mahendra

Reputation: 1426

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]

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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.

Upvotes: 2

Related Questions