(Qt) Validate string against multiple regular expressions simultaneously - c++

I'm checking a string which contains vehicle registration information against regular expressions for validity. I have several regular expression for each criteria I need. How can I validate the string against all my reg expressions without having to combine them into one expression or do something like this to determine if it's valid?
if( s_expGP.exactMatch(lineEdit->text()) ||
s_expGPNew.exactMatch(lineEdit->text()) ||
s_expPersonal.exactMatch(lineEdit->text()) ||
s_expGov.exactMatch(lineEdit->text()) )
{
//do stuff
}

The only option would be to create a single regular expression by combining s_expGP, s_expGPNew, s_expPersonal and the rest if that is possible, otherwise I don't think there could be any other way.

If you have a big number of regexp to test or if you may need to verify the string more than once. You can create a function like this
bool isValid(const QVector<QRegExp>& regExps, const QString& input)
{
for(QRegExp exp : regExps)
{
if(!exp.exactMatch(input))
return false;
}
return true;
}
Or use a static QVector like you have static regexp.

Related

(clang AST matchers) How to match consecutive statements?

I'm planning a bunch of refactorings on a large code base that I'd like to automate using Clang tooling. For this, I'm trying to write a Clang AST Matcher expression.
Specifically, I'm trying to match pairs of statements that I'd like to replace with something else, like
a(); => a_and_b(x);
b(x);
So I'm trying to match an a callExpr() followed by a b callExpr() (but could be any statement, really). I have constructed matchers for the first and the second statements, independently, let's call them aMatcher() and bMatcher() but haven't found how to combine them so that they match only if they're back-to-back, something like bMatcher(follows(aMatcher()). None of the existing matchers seems to be pertinent (looked for "next", "prev", "position", ...).
How do I go about this the correct way, please?
The implementation of UseAnyOfAllOfCheck contains a private nextStmt matcher:
/// Matches a Stmt whose parent is a CompoundStmt, and which is directly
/// followed by a Stmt matching the inner matcher.
AST_MATCHER_P(Stmt, nextStmt, ast_matchers::internal::Matcher<Stmt>,
InnerMatcher) {
DynTypedNodeList Parents = Finder->getASTContext().getParents(Node);
if (Parents.size() != 1)
return false;
auto *C = Parents[0].get<CompoundStmt>();
if (!C)
return false;
const auto *I = llvm::find(C->body(), &Node);
assert(I != C->body_end() && "C is parent of Node");
if (++I == C->body_end())
return false; // Node is last statement.
return InnerMatcher.matches(**I, Finder, Builder);
}
I don't know how robust that is, but I'll try to use it and report back.

Generated getters and setters code format

Is there a way to change format how netbeans 8.1 generate code? Instead of having
void setSomething1(bool something1)
{
something1_ = something1;
}
bool getSomething1() const
{
return something1_;
}
I would like to have this code
void setSomething1(bool something1) { something1_ = something1; }
bool getSomething1() const { return something1_; }
and also the set/get prefix could change or disappear
void setSomething1(bool something1) { something1_ = something1; }
bool something1() const { return something1_; }
netbeans only allow me to change braces position, same line or new line, but for this short functions i would like to compress it to one line only. With many setters and getters, the code starts to be confusing.
If netbeans itself cant do it, would it be possible via regular expression or some other workaroud?
Other (long body) functions will remain in the format. There it makes the code better to read.
retType name(args)
{
body;
}
This regex will satisfy the first requirement (Demo):
([\w ]+\s+[gs]et\w+\([\w ]*\)\s*(?:const)?)\s+\{\s+(.*)\s+\}
With $1 { $2 } as replacement
Then this one (note the trailing space):
get(\w+)\(
With $1 (trailing space aslo) as replacement

How replace If-else block condition

In my code I have an if-else block condition like this:
public String method (Info info) {
if (info.isSomeBooleanCondition) {
return "someString";
}
else if (info.isSomeOtherCondition) {
return "someOtherString";
}
else if (info.anotherCondition) {
return "anotherStringAgain";
}
else if (lastCondition) {
return "string ...";
}
else return "lastButNotLeastString";
}
Each conditional branch returns a String.
Since if-else statements are difficult to read, test and maintain, how can I replace?
I was thinking to use Chain Of Responsability Pattern, is it right in this case?
Is there any other elegant way that I can do that?
I am left to assume that your code does not exist in the Info class as it is passed in an referenced for all but that last condition. My first instinct would be to make String OtherClass.method(Info) into String Info.method() and have it return the appropriate string.
Next, I would take a look at the conditions. Are they really conditions or can they be mapped to a table. Whenever I see code performing a lookup, such as this, I tend to fall back on attempting to fit into a dictionary or map so I can perform a lookup for the value.
If you are left with conditions that must be checked then I would begin thinking about lambdas, delegates or custom interface. A series of if..then across the same type could easily be represented. Next, you would collect them and execute accordingly. IMO, this would make the if..then bunch much clearer. It is more code by is secondary at this point.
interface IInfoCheck
{
bool TryCheck(Info info, out string);
}
public OtherClass()
{
// Setup checks
CheckerCollection.add(new IInfoCheck{
public String check(out result) {
// check code
}
});
}
public String method(Info info) {
foreach (IInfoCheck ic in CheckerCollection)
{
String result = null;
if (ic.TryCheck(out result))
{
return result;
}
}
}
The problem statement does not fit into an ideal chain of responsibility scenario because it is either/or kind or conditions which look 'chained' but is actually 'not'. Reason - one processes all the chain-links in the chain of responsibility pattern irrespective of what happened in the previous links, i.e. no chain-links are skipped(although you can configure which chain links to process and which not - but still the execution of a chain-link is not dependent on the outcome of a previous chain-link). However, in this if-else-if* scenario - once an if statement condition matches, the further conditions are not evaluated.
I have thought of an alternative design which achieves the above without if-else, but it is lengthier but at the same time more flexible.
Lets say we have a FunctionalInterface IfElseReplacer which takes 'info' as input and gives 'String' output.
public Interface IfElseReplacer(){
public String executeCondition(Info);
}
Then the above conditions can be re-phrased as lambda expressions would look like -
"(Info info) -> info.someCondition ? someString"
"(Info info) -> info.anotherCondition ? someOtherString"
and so on...
Then we need a processConditons method to process these Lambdas- it could be a default method in ifElseReplacer -
default String processConditions(List<IfElseReplacer> ifElseReplacerList, Info info){
String strToReturn="lastButNotLeastString";
for(IfElseReplacer ifElseRep:ifElseReplacerList){
strToReturn=ifElseRep.executeCondition(info);
if(!"lastButNotLeastString".equals(strToReturn)){
break;//if strToReturn's value changes i.e. executeCondition returns a String valueother than "lastButNotLeastString" then exit the for loop
}
return strToReturn;
}
What remains now is to (I am skipping the code for this - please let me know if you need it then will write this also) -
From wherever the if-else conditions need to be checked there -
Create an array of lambda expressions as explained above assigning them to IfElseReplacer interfaces while adding them to a list of type IfElseReplacer.
Pass this list to the default method processConditions() along with an instance of Info.
Default method would return the String value which we would be same as the result of if-else-if* block given in the problem statement.
I'd simply factor out the returns:
return
info.isSomeBooleanCondition ? "someString" :
info.isSomeOtherCondition ? "someOtherString" :
info.anotherCondition ? "anotherStringAgain" :
lastCondition ? "string ..." :
"lastButNotLeastString"
;
From the limited information about the problem, and the code given, it looks like this a case of type-switching. The default solution would be to use a inheritance for that:
class Info {
public abstract String method();
};
class BooleanCondition extends Info {
public String method() {
return "something";
};
class SomeOther extends Info {
public String getString() {
return "somethingElse";
};
Patterns which are interesting in this case are Decorator, Strategy and Template Method. Chain of Responsibility has another focus. Each element in the chain implement logic to process some commands. When chained, an object forwards the command if it cannot process it. This implements a loosly coupled structure to process commands where no central dispatch is needed.
If computing the string on the conditions is an operation, and from the name of the class I am guessing that it is probably an expression tree, you should look at the Visitor pattern.

D std.regex - return as text

Is there a possibility to return text which was used to create regular expression?
Something like this:
auto r = regex(r"[0-9]", "g"); // create regular expression
writeln(r.dumpAsText()); // this would write: [0-9]
There is nothing in http://dlang.org/phobos/std_regex.html on this. (or at least I did not notice)
No, because it compiles the regex, and I don't believe it even stores the string after compilation.
The best thing to do is just to store the string yourself on creation.
Source for struct Regex
As you can see, it doesn't store the pattern string, only the bytecode.
Typically using a subtype would work, but unfortunately ti doesn't due to failed template constraints. E.g. a plausible solution (that doesn't work right now) would be to wrap the regex as a subtype:
auto myregex(string arg1, string arg2)
{
struct RegexWrap
{
Regex!char reg;
alias reg this;
string dumpAsText;
}
return RegexWrap(regex(arg1, arg2), arg1);
}
void main()
{
auto r = myregex(r"[0-9]", "g"); // create regular expression
writeln(r.dumpAsText); // this would write: [0-9]
writeln(match("12345", r)); // won't work
}
The match function in std.regex won't work with this wrapper struct even when using a subtype, because it fails this template constraint:
public auto match(R, RegEx)(R input, RegEx re)
is(RegEx == Regex!(BasicElementOf!R)
Even if you changed the header to this, it still won't work:
public auto match(R)(R input, Regex!(BasicElementOf!R) re)
The only way it would work is if the type was explicit so the subtype could be passed:
public auto match(R)(R input, Regex!char re)
I find this to be an awkward part of D that could be improved.

regex with Qt - indexIn(const QString &) does not work as expected

I am using QRegExp and tries to find whether a QString is containing some pattern. There is no compiling error, but no match is identified at runtime where identification should normally happen. I tested the regexp in Python shell and match occurs with Python. i checked upon Qt doc that syntax is the same for the ergexp I am using. Here is code sample
bool Thing::isConstraint(const QString &cstr_)
{
QRegExp lB1("^(\d+\.?\d*|\d*\.\d+)<=PARAM(\d+)$");
QRegExp lB2("^PARAM(\d+)>=(\d+\.?\d*|\d*\.\d+)$");
QRegExp lB3("^PARAM(\d+)>(\d+\.?\d*|\d*\.\d+)$");
QRegExp lB4("^(\d+\.?\d*|\d*\.\d+)<PARAM(\d+)$");
QRegExp uB5("^(\d+\.?\d*|\d*\.\d+)>=PARAM(\d+)$");
QRegExp uB6("^(\d+\.?\d*|\d*\.\d+)>PARAM(\d+)$");
QRegExp uB7("^PARAM(\d+)<=(\d+\.?\d*|\d*\.\d+)$");
QRegExp uB8("^PARAM(\d+)<(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB9("^(\d+\.?\d*|\d*\.\d+)>=PARAM(\d+)>=(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB10("^(\d+\.?\d*|\d*\.\d+)>PARAM(\d+)>=(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB11("^(\d+\.?\d*|\d*\.\d+)>=PARAM(\d+)>(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB12("^(\d+\.?\d*|\d*\.\d+)>PARAM(\d+)>(\\d+\.?\d*|\d*\.\d+)$");
QRegExp luB13("^(\d+\.?\d*|\d*\.\d+)<=PARAM(\d+)<=(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB14("^(\d+\.?\d*|\d*\.\d+)<=PARAM(\d+)<(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB15("^(\d+\.?\d*|\d*\.\d+)<PARAM(\d+)<=(\d+\.?\d*|\d*\.\d+)$");
QRegExp luB16("^(\d+\.?\d*|\d*\.\d+)<PARAM(\d+)<(\d+\.?\d*|\d*\.\d+)$");
int pos_=0;
if((pos_ = lB1.indexIn(cstr_)) != -1)
{
m_func->setLowerBound((lB1.cap(2)).toInt(),(lB1.cap(1)).toDouble());
return true;
}
else if((pos_ = lB2.indexIn(cstr_)) != -1)
{
m_func->setLowerBound((lB2.cap(1)).toInt(),(lB2.cap(2)).toDouble());
return true;
}
/*
...
*/
return false;
}
This method is called in this other method:
void Thing::setConstraints(QStringList &constraints_)
{
if(!m_func)
return;
for(int j=0;j<constraints_.size();j++)
{
if(isConstraint(constraints_.at(j)))
{
constraints_.removeAt(j);
}
}
m_func->setConstraints(constraints_);
}
In VS2010 Watch, error for lB1.indexIn(cstr_) is: Error: argument list does not match a function .
Second, I would like the isConstraint() method to begin with this check and replace for whitespaces:
QRegExp wsp ("\s+");
cstr_.replace(wsp,"");
how to proceed avoiding const_cast ??
Thanks and regards.
edit ---------
needed to double backslash in C++ - different from Python. Tks!
I think you asked two questions, so I'll try to answer them:
1) Your regular expressions are most likely not passing because you need to escape your backslashes so that C++ doesn't mess up your strings. For example:
QRegExp lB1("^(\\d+\\.?\\d*|\\d*\\.\\d+)<=PARAM(\\d+)$");
2) To avoid using const_cast you can either change your function signature to this:
bool Thing::isConstraint( QString cstr_)
or make a copy of the cstr_ object and operate on the copy instead.
As a side note, you may want to take a look at the QRegExp::exactMatch() function which obviates the need to use ^ and $ at the beginning and end of all of your expressions, and also has a bool return value which would make your if statements a little cleaner.