1

I use split in Java like this

String str = "Bx=1946^Cx=1043423"; String[] parts = str.split("^"); for (String part : parts) System.out.println(part); 

But it turns out there is only one element in parts array after splitting, so if I want to use "^" as delimiter, what should I write?

Thanks

2
  • 4
    It doesn't hurt to read the docs :3 Commented Mar 1, 2013 at 17:33
  • 1
    I'd highly recommend using the Apache StringUtils split methods over the standard java ones, especially seeing as they can use regular String delimiters without the potential added confusion of regex. Commented Mar 1, 2013 at 17:36

2 Answers 2

9

You need to escape the^, which has a special meaning in regex (start of word, line and others):

String str = "Bx=1946^Cx=1043423"; String[] parts = str.split("\\^"); for (String part : parts) System.out.println(part); 

The output will be:

Bx=1946 Cx=1043423 
Sign up to request clarification or add additional context in comments.

Comments

2

Use

str.split(Pattern.quote("^")); 

instead of

str.split("^"); 

Pattern.quote() works in case of splitting with multiple symbols too. For example, we can use str.split(Pattern.quote("^^^^")); instead of adding too many special characters like str.split("\\^\\^\\^\\^").

4 Comments

Why do you claim this is a better answer than the accepted answer?
Pattern.quote() works in case of splitting with multiple symbols too. eg: we can use str.split(Pattern.quote("^^^^")); instead of adding too many special characters like str.split("\\^\\^\\^\\^")
@TheThom why not? It does answer the question.
@MarounMaroun It does now. Thanks for the explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.