删除字符串贪婪正则表达式在QT

Remove string with greedy regular expression in QT

本文关键字:QT 正则表达式 贪婪 字符串 删除      更新时间:2023-10-16

事先感谢您的帮助。我是一个新手,所以请原谅我的新手问题。

我想用字符串中的正则表达式"im"替换image1="jdjddsj"。在我的字符串中有更多这样的xx="…",所以我想运行QRegExp greedy,但不知何故似乎不起作用。

QString str_commando;
str_commando = "python python.py image1="sonstzweiteil" one! path="sonstwas" image2="sonsteinanderes" two!"
QString str(str_commando); // The initial string.
qDebug() << str_commando.remove(QRegExp ("age1="([^>]*)""));
/* Set field */
ui->lineeCommand->setText(str_commando);

结果是:pythonpythonpy,我两!

 qDebug() << str_commando.remove(QRegExp ("age1="([^>]*)""));

我以前试过。相同的结果。

我哪里错了?提前感谢您的帮助!

解决方案:

qDebug() << str_commando.replace(QRegExp ("image1="([^"]*)""), "im");

字符集[^>]包含"。这意味着

中的正则表达式
str_commando.remove(QRegExp ("age1="([^>]*)""));

匹配age1="sonstzweiteil" one! path="sonstwas" image2="sonsteinanderes"。如果您确定引号之间没有",则可以设置正则表达式minimal而不是greedy。另一个解决方案是将set [^>]设置为[^>"]。我也不知道你为什么要禁止>

在查看QString的文档后,我认为你也可以这样做:

str_commando.replace(QRegExp("image1="([^"]|\")*""), "im");

或者如果你想要im="...":

str_commando.replace(QRegExp("image1="((?:[^"]|\")*)""), "im="\1"");