Question

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

Was it helpful?

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
        }
    }
}

OTHER TIPS

If you want to do this work with QRegEx, here is the code:

QString reservedList("command1,command2,command3");

QString str = "\\command1 \\command2command1 \\command3 command2 sometext";

QString regString = reservedList;
regString.prepend("(\\\\");      \\ To match the '\' character
regString.replace(',', "|\\\\");
regString.append(")");           \\ The final regString: (\\\\command1|\\\\command2|\\\\command3)
QRegExp regex(regString);
int pos = 0;

while ((pos = regex.indexIn(str, pos)) != -1) {
    qDebug() << regex.cap(0);
    pos += regex.matchedLength();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top