Regex to match sql where conditions

Viewed 101

What should be my Regex to match fetch the WHERE condition without (GROUP\\ BY|HAVING|ORDER\\ BY|ASC|DESC|LIMIT)? It works fine if I have any of the described params. It should also work for both the cases (with or without these parameters)

I need to get id=1 or id=2

QString query = "SELECT * FROM users WHERE id=1 or id=2"
QString whereString;  

QRegularExpression whereListRegex("\\ WHERE\\ (.*?)\\ (GROUP\\ BY|HAVING|ORDER\\ BY|ASC|DESC|LIMIT)\\ ", QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch whereIterator = whereListRegex.match(query);
1 Answers

You may use

QRegularExpression whereListRegex(R"(\sWHERE\s+(.*?)(?:\s+(?:GROUP\s+BY|HAVING|ORDER\s+BY|ASC|DESC|LIMIT)\b|\s*$))", QRegularExpression::CaseInsensitiveOption);

See the regex demo

The regex matches:

  • \s - a whitespace
  • WHERE - a string
  • \s+ - 1+ whitespaces
  • (.*?) - Capturing group 1: any zero or more chars other than linebreak chars as few as possible
  • (?:\s+(?:GROUP\ BY|HAVING|ORDER\ BY|ASC|DESC|LIMIT)\b|\s*$) - either of the two:
    • \s+(?:GROUP\s+BY|HAVING|ORDER\s+BY|ASC|DESC|LIMIT)\b - 1+ whitespaces followed with one of the alternative phrases
    • | - or
    • \s*$ - 0+ whitespaces at the end of string.
Related