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
source to share
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);
}
source to share