Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split the string using '^' this special character in java?

Tags:

java

I want to split the following string "Good^Evening" i used split option it is not split the value. please help me.

This is what I've been trying:

String Val = "Good^Evening";
String[] valArray = Val.Split("^");
like image 791
Manohar Kulanthai vel Avatar asked Dec 18 '11 11:12

Manohar Kulanthai vel


2 Answers

I'm assuming you did something like:

String[] parts = str.split("^");

That doesn't work because the argument to split is actually a regular expression, where ^ has a special meaning. Try this instead:

String[] parts = str.split("\\^");

The \\ is really equivalent to a single \ (the first \ is required as a Java escape sequence in string literals). It is then a special character in regular expressions which means "use the next character literally, don't interpret its special meaning".

like image 69
Oliver Charlesworth Avatar answered Oct 12 '22 14:10

Oliver Charlesworth


The regex you should use is "\^" which you write as "\\^" as a Java String literal; i.e.

String[] parts = "Good^Evening".split("\\^");

The regex needs a '\' escape because the caret character ('^') is a meta-character in the regex language. The 2nd '\' escape is needed because '\' is an escape in a String literal.

like image 20
Stephen C Avatar answered Oct 12 '22 15:10

Stephen C