17

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,037
  • 9
  • 50
  • 71
Julio Diaz
  • 8,355
  • 19
  • 52
  • 69

6 Answers6

54

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

line.split("\\[");
Andrew
  • 13,567
  • 13
  • 64
  • 80
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,037
  • 9
  • 50
  • 71
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,469
  • 2
  • 35
  • 79
3

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

Jagger
  • 10,048
  • 7
  • 47
  • 88
3

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

line.split("\\[");

Mansoor Siddiqui
  • 20,001
  • 9
  • 48
  • 67
0

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