How to compare strings using QString and Qt::MatchFlags for Qt5 and up

The Qt QString class is missing a really great opportunity to use the same Qt::MatchFlags that are used elsewhere in Qt. In the interest of making it super easy to add this functionality to my existing code and yours, just copy the following code into one of your commonly used header files. Make sure to actually include the required headers as shown in the comments. Then you can match your strings using Qt::MatchFlags.


/** determine if the pattern matches the string using Qt::MatchFlags
    \param str the string
    \param pattern the pattern to find
    \param flags any combination of the follow Qt flags
                - Qt::MatchFixedString
                - Qt::MatchContains
                - Qt::MatchStartsWith
                - Qt::MatchEndsWith
                - Qt::MatchRegExp (overrides all flags above)
                - Qt::MatchCaseSensitive
    \returns true if the pattern is found in the string

    requires:
    #include <QString>
    #include <QRegularExpression>
    #include <QRegularExpressionMatch>

    Thank you for visiting sirspot.com
    This code is not guaranteed to work.
    Use at your own risk.
*/
static bool QString_Matches(
    const QString& str,
    const QString& pattern,
    const Qt::MatchFlags& flags = (Qt::MatchCaseSensitive | Qt::MatchFixedString))
{
    if(flags.testFlag(Qt::MatchRegExp) == true)
    {
        QRegularExpression::PatternOptions options = QRegularExpression::NoPatternOption;
        if(flags.testFlag(Qt::MatchCaseSensitive) == false)
        {
            options = QRegularExpression::CaseInsensitiveOption;
        }
        QRegularExpression regex(pattern, options);
        return regex.match(str).hasMatch();
    }
    else
    {
        Qt::CaseSensitivity cs = Qt::CaseSensitive;
        if(flags.testFlag(Qt::MatchCaseSensitive) == false)
        {
            cs = Qt::CaseInsensitive;
        }
        if(flags.testFlag(Qt::MatchContains) == true)
        {
            return str.contains(pattern, cs);
        }
        else
        {
            if(flags.testFlag(Qt::MatchStartsWith) == true)
            {
                if(str.startsWith(pattern, cs) == true)
                {
                    return true;
                }
            }
            if(flags.testFlag(Qt::MatchEndsWith) == true)
            {
                if(str.endsWith(pattern, cs) == true)
                {
                    return true;
                }
            }
            if(flags.testFlag(Qt::MatchFixedString) == true)
            {
                return (str.compare(pattern, cs) == 0);
            }
        }
    }
    return false;
};

Happy String Matching!

Author: sirspot

I write software, love my wife and kids, do various house projects, play video games when I have time, and could use a little more sleep