Krishnendu Ghosh Krishnendu Ghosh - 3 months ago 9
Java Question

Unwanted elements appearing when splitting a string with multiple separators in Java

I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:

String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~@#$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
System.out.println("spart[4]: " + spart[4]);


But, I am getting some elements which are blank. The output is:

spart[0]: s
spart[1]: film
spart[2]:
spart[3]: fever
spart[4]: normal


My desired output is:

spart[0]: s
spart[1]: film
spart[2]: fever
spart[3]: normal
spart[4]: curse

Answer

Try with this:

public static void main(String[] args) {
    String s = "s[film] fever(normal) curse;";
    String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~@#$%^&\\s]+");
    for (String string : spart) {
        System.out.println("'"+string+"'");
    }
}

output:

's'
'film'
'fever'
'normal'
'curse'
Comments