Search code examples
c++qtqstringqregexp

Using QRegExp replace words that are in a QString


I have a QString that contains a list of reserved words. I need to parse another string, seaching for any words that are contained in the first one and are prepended by '\' and modify these ocorrences.

Example:

QString reserved = "command1,command2,command3"

QString a = "\command1 \command2command1 \command3 command2 sometext"

parseString(a, reserved) = "<input com="command1"></input> \command2command1 <input com="command3"></input> command2 sometext"

I know I have to use QRegExp, but I didn't find how to use QRegExp to check if a word is in the list I declared. Can you guys help me out?

Thanks in advance


Solution

  • I would split the reservedWords list into a QStringList then iterate over each reserved word. Then you prepend the \ character (it needs to be escaped in a QString), and use the indexOf() function to see if that reserved word exists in the input string.

    void parseString(QString input, QString reservedWords)
    {
        QStringList reservedWordsList = reserved.split(',');
        foreach(QString reservedWord, reservedWordsList)
        {
            reservedWord = "\\" + reservedWord;
            int indexOfReservedWord = input.indexOf(reservedWord);
            if(indexOfReservedWord >= 0)
            {
                // Found match, do processing here
            }
        }
    }