Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading