String split method
I'm trying to write a method to convert a mathematical expression into a function using Java
I'm starting with really basic functions, i.e.
x^2 + x + 2
now as a starting point, I'm hoping to split the String i.e.
"x^2 + x + 2"
using the split method of the String class, now given I was to split using the addition symbols I thought I would use
"x^2 + x + 2".split("+");
however this produces the following error (using Netbeans)
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
at java.util.regex.Pattern.sequence(Pattern.java:1878 )
Java Result: 1
Was just wondering if this can be overcome with the split method?
Thanks in Advance,
Check out the Pattern API to figure out how to use regular expressions.
Pattern (Java Platform SE 6)
Thanks for linking that, Sorry I'm fairly new to Java and am still puzzled by this :-(
When I try
Pattern p = Pattern.compile("+")
I get a similar error as before, I'm sure I'm missing something simple - any further suggestions would be greatly appreciated.
The '+' character has a special meaning in regular expressions: it's the transitive closure of a regular expression: 'one or more times'. You have to escape it to make it an ordinary character: "\\+".
Originally Posted by DavidG24
Uh, yeah. That error would be expected. What does the API say about using a "+" symbol? What does it say about escaping literals?
Edit- Jos made it easy for you. :p
cheers for that mate! working now :-)
And thanks again Kevin..