15

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("^");
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287

3 Answers3

33

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".

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
7

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

try this

String str = "Good^Evening";
String newStr = str.replaceAll("[^]+", "");