Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.split() a string containing the characters "++" [duplicate]

Tags:

java

regex

split

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.

like image 936
ltd9938 Avatar asked Mar 05 '23 01:03

ltd9938


1 Answers

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]);
like image 108
Nikolas Charalambidis Avatar answered Mar 11 '23 12:03

Nikolas Charalambidis