klemens
klemens

Reputation: 413

Java and string split

split this String using function split. Here is my code:

String data= "data^data";
String[] spli = data.split("^");

When I try to do that in spli contain only one string. It seems like java dont see "^" in splitting. Do anyone know how can I split this string by letter "^"?

EDIT

SOLVED :P

Upvotes: 4

Views: 221

Answers (5)

DaveFar
DaveFar

Reputation: 7467

The reason is that split's parameter is a regular expression, so "^" means the beginning of a line. So you need to escape to ASCII-^: use the parameter "\\^".

Upvotes: 2

Dawood
Dawood

Reputation: 5316

Special characters like ^ need to be escaped with \

Upvotes: 3

MAK
MAK

Reputation: 26586

This does not work because .split() expects its argument to be a regex. "^" has a special meaing in regex and so does not work as you expect. To get it to work, you need to escape it. Use \\^.

Upvotes: 2

Joey
Joey

Reputation: 354824

This is because String.split takes a regular expression, not a literal string. You have to escape the ^ as it has a different meaning in regex (anchor at the start of a string). So the split would actually be done before the first character, giving you the complete string back unaltered.

You escape a regular expression metacharacter with \, which has to be \\ in Java strings, so

data.split("\\^")

should work.

Upvotes: 7

Jigar Joshi
Jigar Joshi

Reputation: 240966

You need to escape it because it takes reg-ex

\\^

Upvotes: 3

Related Questions