Search code examples
qthexqstring

Qt Check QString to see if it is a valid hex value


I'm working with Qt on an existing project. I'm trying to send a string over a serial cable to a thermostat to send it a command. I need to make sure the string only contains 0-9, a-f, and is no more or less than 6 characters long. I was trying to use QString.contains, but I'm am currently stuck. Any help would be appreciated.


Solution

  • You have two options:

    Use QRegExp

    Use the QRegExp class to create a regular expression that finds what you're looking for. In your case, something like the following might do the trick:

    QRegExp hexMatcher("^[0-9A-F]{6}$", Qt::CaseInsensitive);
    if (hexMatcher.exactMatch(someString))
    {
       // Found hex string of length 6.
    }
    

    ###Update### Qt 5 users should consider using QRegularExpression instead of QRegExp:

    QRegularExpression hexMatcher("^[0-9A-F]{6}$",
                                  QRegularExpression::CaseInsensitiveOption);
    QRegularExpressionMatch match = hexMatcher.match(someString);
    if (match.hasMatch())
    {
        // Found hex string of length 6.
    }
    

    Use QString Only

    Check the length of the string and then check to see that you can convert it to an integer successfully (using a base 16 conversion):

    bool conversionOk = false;
    int value = myString.toInt(&conversionOk, 16);
    if (conversionOk && myString.length() == 6)
    {
       // Found hex string of length 6.
    }