Julio Diaz
Julio Diaz

Reputation: 9437

Split using a bracket

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?

Upvotes: 22

Views: 63081

Answers (6)

Kapil Chauhan
Kapil Chauhan

Reputation: 1

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

Upvotes: 0

Mansoor Siddiqui
Mansoor Siddiqui

Reputation: 21703

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

line.split("\\[");

Upvotes: 4

G_H
G_H

Reputation: 12019

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.

Upvotes: 6

Jagger
Jagger

Reputation: 10522

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

Upvotes: 3

Andrew
Andrew

Reputation: 13863

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

line.split("\\[");

Upvotes: 63

FailedDev
FailedDev

Reputation: 26940

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.

Upvotes: 6

Related Questions