使用QRegExp替换QString中的单词

时间:2013-07-19 17:21:48

标签: c++ qt qstring qregexp

我有一个包含保留字列表的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来检查我声明的列表中是否有单词。你能帮助我吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

我会将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
        }
    }
}

答案 1 :(得分:1)

如果您想使用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();
}