我希望QString允许这样做:
QString myString("School is LameCoolLame and LameRadLame");
myString.replace(QRegularExpression("Lame(.+?)Lame"),"\1");
离开
"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));
}
}
这似乎没有效果,(我实际上放弃了)。必须有一种更方便的方式。为了简单起见和代码可读性,我想知道采用最少行代码来完成此任务的方法。
感谢。
答案 0 :(得分:6)
QString myString("School is LameCoolLame and LameRadLame");
myString.replace(QRegularExpression("Lame(.+?)Lame"),"\\1");
Above code works as you expected. In your version, you forgot to escape the escape character itself.