Java split doesn't work correctly with ^

I want to split the string for a character ^

, but that doesn't work. I have the following code:

String numberBase10 = "3.52*10^2";
String[] vector = numberBase10.split("^"); 
System.out.println("numberBase10: " + numberBase10);
System.out.println("Vector[0]: " vector[0]);

      

I am getting the following output:

numberBase10: 3.52*10^2
Vector[0]: 3.52*10^2

      

And if I try to access vector [1], I get an IndexOutOfArray error.

Do I need to put any escape character for the split to work with ^

?

thank

+3


source to share


5 answers


You need to avoid this with \\^

.



^ is a special character by itself, which means negation (in a group such as [^ abc], which matches anything other than abc) or an anchor for the beginning of a string.

+8


source


split

accepts a regular expression. ^

is an anchor used to match the beginning of a string in a regex, so it needs to be escaped



String[] vector = numberBase10.split("\\^");

      

+8


source


The java string splitting method works with regex and '^' is the anchor character in regex, so it needs to be escaped to treat it like a regular character:

String[] vector = numberBase10.split("\\^");

      

+2


source


^

is a special character as a regex you need to escape it - if I go to

String[] vector = numberBase10.split("\\^");

      

Then I get

Vector[0]: 3.52*10

      

Without any code changes.

+1


source


Since the method split()

expects a regex, if you want to split into an exact string without worrying about any special regex characters it may contain, you should first avoid it with

String regex = java.util.regex.Pattern.quote("^");

Then divide by regex

. The whole concept can be packaged into a nice static method:

public static String[] splitRaw(String input, String separator) {
    String regex = java.util.regex.Pattern.quote(separator);
    return input.split(regex);
}

      

+1


source







All Articles