Reputation: 3441
How to escape + character while using split function call in java?
split declaration
String[] split(String regularExpression)
thats what i did
services.split("+"); //says dongling metacharacter
services.split("\+"); //illegal escape character in string literal
But it allows to do something like this
String regExpr="+";
Upvotes: 11
Views: 6696
Reputation: 138
Java and Regex both have special escape sequences, and both of them begin with \
.
Your issue lies in writing a string literal in Java. Java's escape sequences are resolved at compile time, long before the string is passed into your Regex engine for parsing.
The sequence "\+"
would throw an error as this is not a valid Java string.
If you want to pass \+
into your Regex engine you have to explicitly let Java know you want to pass in a backslash character using "\\+"
.
All valid Java escape sequences are as follows:
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a formfeed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
Upvotes: 2
Reputation: 62854
Since the +
is a regex meta-character (denoting an occurrence of 1 or more times), you will have to escape it with \
(which also has to be escaped because it's a meta-character that's being used when describing the tab character, the new line character(s) \r\n
and others), so you have to do:
services.split("\\+");
Upvotes: 6