-1

I want to split a string in Java with the following format: "value^1" so that I get the initial part, "value" in a string.

I wanted to use split instead of substring, so I tried this:

string.split("^")[0]

but unfortunately ^ is a special character and I guess it has to be escaped. I tried split("\^") but no luck.

Anybody knows how to achieve this using split?

Thanks!

David
  • 3,364
  • 10
  • 41
  • 84
  • You need to escape the `^` in the regex but you also need to escape the `\` in the String with `\` so you end up with `\\^`. – AxelH Nov 17 '16 at 14:01

1 Answers1

3

Escape the escape: split("\\^"). Or split(Pattern.quote("^")).

But since you only want the first part of it, there's no need to use split:

int pos = string.indexOf('^');
String firstPart = (pos != -1) ? string.substring(0, pos) : string;
Andy Turner
  • 137,514
  • 11
  • 162
  • 243