tags:

views:

86

answers:

2

I want to split a string with "?" as the delimitter.

str.split("?")[0] fails.

+2  A: 
str.split("\\?")[0]
LukeH
(Explanation: the argument to `String.split` is actually a regular expression and not plain text. Not one of Java's best bits of design, this.)
bobince
... because `?` is a special character in regular expressions it has to be escaped with \ and \ has to be escaped with \ in Java.
splash
@Downvoter: Care to explain why?
LukeH
maybe because the split method does not have a capital S? :)
Fortega
@Fortega: Thanks for the edit. If I downvoted every time I encountered a typo on this site then I reckon my index finger would have worn away by now!
LukeH
I agree, LukeH...
Fortega
+10  A: 

The argument to the "split" method must be a regular expression, and the '?' character has special meaning in regular expressions so you have to escape it. That's done by adding a backslash before it in the regexp. However, since the regexp is being supplied by way of a Java String, it requires two backslashes instead so as to get an actual backslash character into the regexp:

str.split( "\\?" )[0];
ishnid
+1 for explaining *why* you need to escape `?`, rather than just giving code.
FrustratedWithFormsDesigner