2

Just found out, that I get a NullPointerException when trying to split a String around +, but if I split around - or anything else (and change the String as well of course), it works just fine.

String string = "Strg+Q";
String[] parts = string.split("+");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q

Would love to hear from you guys, what I am doing wrong!

This one works:

String string = "Strg-Q";
String[] parts = string.split("-");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Bambi
  • 139
  • 8

8 Answers8

4

As + is one of the special regex syntaxes you need to escape it. Use

String[] parts = string.split("\\+");

Instead of

String[] parts = string.split("+");
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
3

It happens because + is a special character in Regex - it's the match-one-or-more quantifier.

The only thing you need to do is to escape it:

String[] parts = string.split("\\+");
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
3

String.split(...) expects a Regular Expression and the '+' is a special character. Try:

 String string = "Strg+Q";
 String[] parts = string.split("[+]");
 String part1 = parts[0]; //Strg
 String part2 = parts[1]; //Q
3

Try this:

final String string = "Strg+Q";
final String[] parts = string.split("\\+");
System.out.println(parts[0]); // Strg
System.out.println(parts[1]); // Q
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Arun
  • 3,701
  • 5
  • 32
  • 43
2

+ is a special regex character which means that you need to escape it in order to use it as a normal character.

 String[] parts = string.split("\\+");
Turamarth
  • 2,282
  • 4
  • 25
  • 31
2

The problem you got here is that "+" is a meta character in Java, so you need to "scape" it by using "\\+".

A.Martinez
  • 133
  • 2
  • 12
2

As others have mentioned, '+' is special when dealing with regex. In general, if a character is special you can use Pattern.quote() to escape it, as well as "\\+". Documentation on Pattern: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Example:

String string = "Strg-Q";
String[] parts = string.split(Pattern.quote("+"));
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Qenter code here

Remember to import pattern from java.util.regex!

SmoothJazz
  • 21
  • 3
1

Amit beat me too it. string.split() takes a regular expression as its argument. In regexes + is a special symbol. Escape it with a backslash. Then, since it's a java string, escape the backslash with another backslash, so you get \+. Try testing your regular expressions on an online regex tester.

Brent Sandstrom
  • 841
  • 10
  • 16