21

How can I split a string using [ as the delimiter?

String line = "blah, blah [ tweet, tweet";

if I do

line.split("[");

I get an error

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 1 [

Any help?

FailedDev
  • 26,680
  • 9
  • 53
  • 73
Julio Diaz
  • 9,067
  • 19
  • 55
  • 70

6 Answers6

60

The [ is a reserved char in regex, you need to escape it,

line.split("\\[");
Andrew
  • 13,757
  • 13
  • 66
  • 84
6

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.

FailedDev
  • 26,680
  • 9
  • 53
  • 73
6

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.

G_H
  • 11,739
  • 3
  • 38
  • 82
4

The [ character is interpreted as a special regex character, so you have to escape it:

line.split("\\[");

Mansoor Siddiqui
  • 20,853
  • 10
  • 48
  • 67
3

Please use "\\[" instead of "[".

Jagger
  • 10,350
  • 9
  • 51
  • 93
0

if have to split between [] then try str.split("[\\[\\]]");