Mendy
Mendy

Reputation: 15

Split certain parts of string with different divider signs

So for instance if I have:

String test = "test DE;IT;ES;CH;AU;FR";

With String[] split = test.split("\\W"); I could split the string and put the individual parts of the string into an array.

However what I want is that for instance if I have the same String:

String test2 = "test DE; IT;ES ;CH;AU;FR";

but this time there are random spaces in between. I want to keep those spaces. The issue is if I only use ; as a regex the first word would be test DE instead of test being an own string and DE being an own String.

So my desired result for an array would be in this case: [test,DE, IT,ES ,CH,AU,FR] (I removed the standard spaces after the comma to make it more clear)

Upvotes: 1

Views: 47

Answers (2)

MonkeyZeus
MonkeyZeus

Reputation: 20747

You can make use of lookarounds:

;|(?<!;) +(?!;)

https://regex101.com/r/e0ZtAa/1

Upvotes: 0

JvdV
JvdV

Reputation: 75870

You could use:

;|\b +\b

See an online demo


import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
      String test = "test DE; IT;ES ;CH;AU;FR";
      String[] split = test.split(";|\\b +\\b");
      System.out.println(Arrays.toString(split));
    }
}

Prints:

[test, DE,  IT, ES , CH, AU, FR]

Upvotes: 1

Related Questions