在 Qt 中,用正则表达式捕获替换字符串匹配所需的代码量最少?

In Qt, what takes the least amount of code to replace string matches with regular expression captures?

我希望 QString 允许这样做:

QString myString("School is LameCoolLame and LameRadLame");
myString.replace(QRegularExpression("Lame(.+?)Lame"),"");

离开

"School is Cool and Rad"

与我在文档中看到的相反,这样做要复杂得多,需要您执行(来自文档):

QRegularExpression re("\d\d \w+");
QRegularExpressionMatch match = re.match("abc123 def");
if (match.hasMatch()) {
    QString matched = match.captured(0); // matched == "23 def"
    // ...
}

或者在我的情况下是这样的:

QString myString("School is LameCoolLame and LameRadLame");
QRegularExpression re("Lame(.+?)Lame");
QRegularExpressionMatch match = re.match(myString);
if (match.hasMatch()) {
    for (int i = 0; i < myString.count(re); i++) {
        QString newString(match.captured(i));
        myString.replace(myString.indexOf(re),re.pattern().size, match.captured(i));
    }
}

这似乎根本行不通(实际上我放弃了)。必须有更简单更方便的方法。为了简单和代码的可读性,我想知道用最少的代码行来完成这个的方法。

谢谢。

QString myString("School is LameCoolLame and LameRadLame");
myString.replace(QRegularExpression("Lame(.+?)Lame"),"\1");

以上代码如您所愿。在您的版本中,您忘记了对转义字符本身进行转义。