3

I want to split a string for the character ^ but it does not 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 get the following output:

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

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

I have to put any escape character so that split works with ^?

Thanks

Ingrid
  • 741
  • 2
  • 8
  • 15

5 Answers5

8

You need to escape it with \\^.

^ is a special character by itself, meaning negation (in a group, such as [^abc], which matches anything but abc) or the anchor for beginning of line.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
8

split takes a regular expression. ^ is an anchor used to match the start of string in regex so needs to be escaped

String[] vector = numberBase10.split("\\^");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

The java string split method operates on a regex, and '^' is an anchor character in a regex so it must be escaped to treat it as a regular character:

String[] vector = numberBase10.split("\\^");
rdowell
  • 729
  • 4
  • 15
1

The ^ is a special character as regular expression, you need to escape it - If I change to,

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

Then I get

Vector[0]: 3.52*10

With no other code changes.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Since the split() method expects a regular expression, if you want to split on an exact string without worrying about any regex special characters it may contain, you should escape it first with

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

Then split on regex. The whole concept can be packaged up in a nice static method:

public static String[] splitRaw(String input, String separator) {
    String regex = java.util.regex.Pattern.quote(separator);
    return input.split(regex);
}
x-code
  • 2,940
  • 1
  • 18
  • 19