使用QRegExp替换QString中的单词

Using QRegExp replace words that are in a QString

本文关键字:单词 QString QRegExp 替换 使用      更新时间:2023-10-16

我有一个包含保留字列表的QString。我需要解析另一个字符串,查找第一个字符串中包含的、以"\"开头的任何单词,并修改这些单词。

示例:

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"

我知道我必须使用QRegExp,但我没有找到如何使用QRegExp来检查我声明的列表中是否有单词。你们能帮我吗?

提前感谢

我会将reservedWords列表拆分为QStringList,然后对每个保留字进行迭代。然后在字符之前加上前缀(需要在QString中转义),并使用indexOf()函数查看输入字符串中是否存在保留字。

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

如果你想用QRegEx做这项工作,下面是代码:

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();
}