Roy Hinkley
Roy Hinkley

Reputation: 10651

Splitting a string with java not working

I have a string in java that looks something like:

holdingco^(218) 333-4444^[email protected]

I set a string variable equal to it:

String value = "holdingco^(218) 333-4444^[email protected]";

Then I want to split this string into it's components:

String[] components = value.split("^");

However it does not split up the string. I have tried escaping the carrot delimiter to no avail.

Upvotes: 0

Views: 210

Answers (2)

asa
asa

Reputation: 4040

try with: value.split("\\^"); this should work a bit better

Upvotes: 0

jlordo
jlordo

Reputation: 37843

Use

String[] components = value.split("\\^");

The unescaped ^ means beginning of a string in a regex, and the unescaped $ means end. You have to use two backslashes for escaping, as the string literal "\\" represents a single backslash, and that's what regex needs.

If you tried escaping with one backslash, it didn't compile, as \^ is not a valid escape sequence in Java.

Upvotes: 8

Related Questions