Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape + character in java?

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="+";
like image 528
Sandeep Rana Avatar asked Aug 20 '15 08:08

Sandeep Rana


People also ask

How do you escape an escape character in Java?

So in a character literal, you need to escape single quotes, e.g. '\'' . So all you need is "\\'" , escaping only the backslash.

How do you escape characters?

Escape CharactersUse the backslash character to escape a single character or symbol.

What do \n and \t do in Java?

These are escape characters which are used to manipulate string. \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.


1 Answers

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("\\+");
like image 187
Konstantin Yovkov Avatar answered Oct 05 '22 09:10

Konstantin Yovkov