4

Suppose I have this block of code:

String x = "Hello ++ World!"; if(x.contains(" ++ ")) System.out.println(x.split(" ++ ")[0]); 

Why is it that when I execute this code I receive the output:

  • Hello ++ World! instead of Hello?

It obviously has something to do with the split(), however, I can't figure it out.

2
  • 3
    split accepts a regular expression. The + character is a character with a special meaning in the context of regular expressions. Commented May 3, 2019 at 14:15
  • 4
    String.split(String) treats the parameter as a regular expression where + has a special meaning. Try split(" \\+\\+ ") or split(Pattern.quote(" ++ ")) instead. Commented May 3, 2019 at 14:15

3 Answers 3

8

The method String::split uses Regex for the split. Your expression " ++ " is a Regex and the + character has a special meaning. From the documentation:

Splits this string around matches of the given regular expression.

You have to escape these characters:

System.out.println(x.split(" \\+\\+ ")[0]); 
Sign up to request clarification or add additional context in comments.

1 Comment

Using Pattern.quote like Thomas recommended above is even better.
0

Because ++ it's interpreted as a regular expression. You need to escape it with backslash. Try this:

System.out.println(x.split(" \\+\\+ ")[0]);

2 Comments

Well, that doesn't work, because \ is also an escape character in Java, so you need to escape the backslashes as well.
Thanks for pointing that out. I am sure I have added 2 backslashes though..
-1

Split method uses a regexp as argument, you should escape special characters like +. Try something like:

 String x = "Hello ++ World!"; if(x.contains(" ++ ")) System.out.println(x.split("\\s\\+\\+\\s")[0]); 

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.