-
Hi,
My aim to check whether a user has entered the input correctly. The input is a std::string which should be a polynomial. The following are two examples of what should be valid or invalid:std::string sample1 = {"4x^3 - 9x^2 + 10x^1 -5x^0 -45x^-1"}; // valid std::string sample2 = {"4x^3 - 9x^2 + 10x -5 -45x^-1"};// invalid
Right now I am trying to use std::regex to verify this:
bool verifyPolynomial(const std::string& poly){ // Used when your searching a string std::smatch matches; std::regex _regex("[0-9]+[a-z]+\\^[0-9]");// I don't think this is correct? std::regex_search(poly, matches, _regex); return matches.size(); }
I am learning regex, so I find this a bit confusing if someone can help that would be great
-
Hi,
My aim to check whether a user has entered the input correctly. The input is a std::string which should be a polynomial. The following are two examples of what should be valid or invalid:std::string sample1 = {"4x^3 - 9x^2 + 10x^1 -5x^0 -45x^-1"}; // valid std::string sample2 = {"4x^3 - 9x^2 + 10x -5 -45x^-1"};// invalid
Right now I am trying to use std::regex to verify this:
bool verifyPolynomial(const std::string& poly){ // Used when your searching a string std::smatch matches; std::regex _regex("[0-9]+[a-z]+\\^[0-9]");// I don't think this is correct? std::regex_search(poly, matches, _regex); return matches.size(); }
I am learning regex, so I find this a bit confusing if someone can help that would be great
@HFT_developer
This is not an easy one for a beginner! Try playing with https://regex101.com, where you can test regular expressions against whatever input you give it.The final answer depends on how strict you want to be, what you do/do not want to allow, whether it must match the whole, complete string, how you want to handle whitespace, and so on.
I see your attempt as close:
[0-9]+[a-z]+\^-?[0-9]+
might do you for each polynomial in the expression.
Then you may have to go:
[0-9]+[a-z]+\^-?[0-9]+(\s*[+-]\s*[0-9]+[a-z]+\^-?[0-9]+)*
to do the series of polys separated by a
+
or-
symbol. Or something like that :) -
Hi,
Qt also have QRegularExpression for that kind of work and there's a helper tool that you can build to test your expressions.
-
mathematically speaking both expressions are valid. -5x^0 evalutates to -5 so the term is the same even if it is expressed differently.