How can I split a string using [
as the delimiter?
String line = \"blah, blah [ tweet, tweet\";
if I do
line.
Please use "\\["
instead of "["
.
The split
method operates using regular expressions. The character [
has special meaning in those; it is used to denote character classes between [
and ]
. If you want to use a literal opening square bracket, use \\[
to escape it as a special character. There's two slashes because a backslash is also used as an escape character in Java String literals. It can get a little confusing typing regular expressions in Java code.
The [
character is interpreted as a special regex character, so you have to escape it:
line.split("\\[");
Just escape it :
line.split("\\[");
[
is a special metacharacter in regex which needs to be escaped if not inside a character class such as in your case.
The [
is a reserved char in regex, you need to escape it,
line.split("\\[");