Reputation: 9437
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
Reputation: 21703
The [
character is interpreted as a special regex character, so you have to escape it:
line.split("\\[");
Upvotes: 4
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
Reputation: 13863
The [
is a reserved char in regex, you need to escape it,
line.split("\\[");
Upvotes: 63
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