• Post Reply Bookmark Topic Watch Topic
  • New Topic

Splitting a string by a character  RSS feed

 
Stephen McElligott
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to use the split method to split a string for a calculator, but it keeps throwing this Exception:
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+

 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String you pass as an argument to the String.split() method will be interpreted as a regular expression.
If you look at the Pattern class, you'll notice that the + is actually a meta-character used for greedy, reluctant or possessive matching by the regex engine.
In other words, if you want the + to just be interpreted as a character you'll have to let the regex engine know somehow.
That is where the escape character \ comes in. The proper regular expression would be \+ in this case, but there's one more gotcha!
Java itself will also interpret the \ character inside a String literal as the start of an escape sequence, so you'll need to escape your escape...
The regex String you're looking for is therefor "\\+".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!