Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in java for delimiter

My question is that I want to split string in java with delimiter ^. And syntax which I am using is:

readBuf.split("^");

But this does not split the string.Infact this works for all other delimiters but not for ^.

like image 989
salman khalid Avatar asked Dec 10 '22 05:12

salman khalid


2 Answers

split uses regular expressions (unfortunately, IMO). ^ has special meaning in regular expressions, so you need to escape it:

String[] bits = readBuf.split("\\^");

(The first backslash is needed for Java escaping. The actual string is just a single backslash and the caret.)

Alternatively, use Guava and its Splitter class.

like image 156
Jon Skeet Avatar answered Dec 14 '22 23:12

Jon Skeet


Use \\^. Because ^ is a special character indicating start of line anchor.

String x = "a^b^c";
System.out.println(Arrays.toString(x.split("\\^"))); //prints [a,b,c]
like image 28
Narendra Yadala Avatar answered Dec 15 '22 00:12

Narendra Yadala