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

How can I split this line into an Array without having an empty element?

Here is the line

String text = " !!!.. first, second: third";

Here is my method

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

  public static String[] splitWords(String text) {
        if (text == null ) return null;
        if(text.isBlank() || text.isEmpty()) return null;
        if(text.matches("[.;,:?!\\s]+")) return null;

         String[] splitRaw = text.trim().split("[.;,:?!\\s]+");

        System.out.println(Arrays.toString(splitRaw));
        return splitText;
    }

Here is the result:
"[, first, second, third]"

As you can see, one empty element is in the start of the array. Array length should be 3, but it’s 4.

>Solution :

Your regex is fine and the empty string is unavoidable in this case, if you want to make sure there aren’t any in the result, you can always stream, filter and recollect it:

public static String[] splitWords(String text) {
    if (text == null ) return null;
    if(text.isBlank() || text.isEmpty()) return null;
    if(text.matches("[.;,:?!\\s]+")) return null;
    return Arrays.stream(text.trim().split("[.;,:?!\\s]+"))
        .filter(s -> !s.equals("")).toArray(String[]::new);
}
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