Question

I am trying break a String in various pieces using delimiter(":").

    String sepIds[]=ids.split(":");

It is working fine. But when I replace ":" with " * " and use " * " as delimiter, it doesn't work.

    String sepIds[]=ids.split("*"); //doesn't work

It just hangs up there, and doesn't execute further.

What mistake I am making here?

Was it helpful?

Solution 2

String.split expects a regular expression argument. * has got a meaning in regex. So if you want to use them then you need to escape them like this:

String sepIds[]=ids.split("\\*");

OTHER TIPS

String#split takes a regular expression as parameter. In regex some chars have special meanings so they need to be escaped, for example:

"foo*bar".split("\\*")

the result will be as you expect:

[foo, bar]

You could also use the method Pattern#quote to simplify the task.

"foo*bar".split(Pattern.quote("*"))

The argument of .split() is a regular expression, not a string literal. Therefore you need to escape * since it is a special regex character. Write:

ids.split("\\*");

This is how you would split agaisnt one or more spaces:

ids.split("\\s+");

Note that Guava has Splitter which is very, very fast and can split against literals:

Splitter.on('*').split(ids);

'*' and '.' are special characters you have to blackshlash it.

String sepIds[]=ids.split("\\*");

To read more about java patterns please visit that page.

That is expected behaviour. The documentation for the String split function says that the input string is treated as a regular expression (with a link explaining how that works). As Germann points out, '*' is a special character in regular expressions.

Java's String.split() uses regular expressions to split up the string (unlike similar functions in C# or python). * is a special character in regular expressions and you need to escape it with a \ (backslash). So you should use instead:

String sepIds[]=ids.split("\\*");

You can find more information on regular expressions anywhere on the internet a quite complete list of special characters supported by java should be here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

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