Question

I have a simple problem. String looks like this:

storm, whatever1, fire,water and something else,earth

I would like to use String.split(" ... ") and split line for "," or "space + ,". Just dont want to have any space in any of string. Result should be

String s[] = {"storm","whatever1","fire","water and something else","earth"};

Is it possible using regex?

Was it helpful?

Solution

Split using \\s*,\\s*. This will split on each , including zero or more (*) whitespaces ("\\s") surrounding it from each side.

OTHER TIPS

This is what you need:

public class Test
{
    public static void main(String[] args)
    {
        String source = "storm, whatever1, fire,water and something else,earth";
        for (String piece : source.split("\\s*,\\s*"))
        {
            System.out.println(piece);
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top