gpt4 book ai didi

regex - 在 Qt 中,用最少的代码用正则表达式捕获替换字符串匹配是什么?

转载 作者:行者123 更新时间:2023-12-03 15:04:34 25 4
gpt4 key购买 nike

我希望 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));
}
}

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

谢谢。

最佳答案

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

上面的代码按您的预期工作。在您的版本中,您忘记转义转义字符本身。

关于regex - 在 Qt 中,用最少的代码用正则表达式捕获替换字符串匹配是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33669234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com