I'm trying to parse polynomials into their individual terms, e.g. "3x+2" into "3x" and "2", using regular expressions. However, I've no experience with Java regex. The code I've come up with below, after consulting the SDK is
The Match object is returning no match, although I've tested that expression using a 3rd party regex checker and it works. Am I using the Match or Pattern classes incorrectly? Any tips for regex in general are also welcome.
Scheepers, I'm sorry to say your solution has several problems. Within a character class, most of the characters that usually have special meaning, don't. So there's no need to escape the '*', '+', '/' characters--but you should have escaped the '-' because character classes use it to define a range, as in "[a-z]" (but if it's the very first or last character in the set, the hyphen gets treated as a literal character). The '|' shouldn't be in there at all: the OR is implicit in a character class, so the pipe just gets treated a another literal character. Also, when you're creating a regex in a String literal, you have to use two backslashes to escape a character, not one.
Jim, the lookingAt() method means the regex matches the beginning of the target text, but not necessarily all of it. You probably want the find() method, which looks for the next match anywhere with the target. Here's a sample app to demonstrate: Also, input.substring(match.start(),match.end()) is exactly the same as match.group().
Scheepers de Bruin
Joined: Jul 19, 2005
I stand corrected
(So when is someone building a sample-code-compiler for the ranch to verify?) =)
well you will have problems with polynomials how do you propose to match the constant coefficients with their respective powers of x? for example 2x^2 + 3x + 5 might also come in as 3x + 2x^2 +5 do you allow only linear polynomials? and are you assured that the order will always be in the decreasing powers of x? and that they will be the most simplified form? of course these don't come in as regex problems, but just thought I should mention them too.
"It's not enough that we do our best; sometimes we have to do<br />what's required."<br /> <br />-- Sir Winston Churchill