4

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

2
  • With SO you need to mark the answer which is really an answer for your question by clicking mark near to the answer Commented Jan 28, 2012 at 9:23
  • Jigar, it's recommended but not required. Commented Jan 28, 2012 at 12:05

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to escape it because it takes reg-ex

\\^

Comments

3

Special characters like ^ need to be escaped with \

1 Comment

actually escapped with \\, because of java
2

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 \\^.

Comments

2

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 "\\^".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.