Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split on ^ (caret?) not working, is this a special character?

Tags:

java

split

In Java, I am trying to split on the ^ character, but it is failing to recognize it. Escaping \^ throws code error.

Is this a special character or do I need to do something else to get it to recognize it?

String splitChr = "^"; String[] fmgStrng = aryToSplit.split(splitChr);  
like image 844
art vanderlay Avatar asked May 22 '12 02:05

art vanderlay


People also ask

How do you split special characters?

To split a string by special characters, call the split() method on the string, passing it a regular expression that matches any of the special characters as a parameter. The method will split the string on each occurrence of a special character and return an array containing the results. Copied!

Why split is not working for dot in Java?

backslash-dot is invalid because Java doesn't need to escape the dot. You've got to escape the escape character to get it as far as the regex which is used to split the string.

What does split () does in Java?

The split() method divides the string at the specified regex and returns an array of substrings.


1 Answers

The ^ is a special character in Java regex - it means "match the beginning" of an input.

You will need to escape it with "\\^". The double slash is needed to escape the \, otherwise Java's compiler will think you're attempting to use a special \^ sequence in a string, similar to \n for newlines.

\^ is not a special escape sequence though, so you will get compiler errors.

In short, use "\\^".

like image 115
逆さま Avatar answered Oct 13 '22 00:10

逆さま