【问题标题】:Choose only one option between double brackets QString [closed]在双括号 QString 之间仅选择一个选项 [关闭]
【发布时间】:2013-09-26 00:56:05
【问题描述】:

我想清理 QString 数据以获得以下内容:

输入

[[normal]], here's [[double phrased|brackets]]

输出

normal, here's double phrased

只需选择每个子括号中的第一个元素即可。我不确定执行此操作的最佳方法是什么?

另外,我使用的是 Qt 4,所以这需要由 QRegExp 完成。

【问题讨论】:

  • 您的问题得到答案了吗?

标签: c++ qt qt4 qstring qregexp


【解决方案1】:

main.cpp

#include <QString>
#include <QDebug>
#include <QRegExp>

int main()
{
    QRegExp rx("\\[{2}([^\\]\\|]+)(\\|[^\\]\\|]+)*\\]{2}");
    QString mystr = "[[normal]], here's [[double phrased|brackets]]";

    for (int pos = 0; (pos = rx.indexIn(mystr, pos)) != -1; pos += rx.matchedLength())
        mystr.replace(pos, rx.matchedLength(), rx.cap(1));

    qDebug() << mystr;

    return 0;
}

编译

您可能需要稍有不同的命令,但这仅供参考,以便您可以根据自己的环境进行调整:

g++ -I/usr/include/qt4/QtCore -I/usr/include/qt4 -fPIC -lQtCore main.cpp && ./a.out

输出

"normal, here's double phrased"

请注意,使用 Qt 5,您可能应该稍后集中到 QRegularExpression

另外,这是一个很好的例子,说明为什么在某些情况下避免使用正则表达式是好的。在此处编写替换功能将花费我们更少的时间,并且最终结果将更具可读性,因此可维护。

感谢 lancif 的原创灵感。

【讨论】:

    猜你喜欢
    • 2015-02-26
    • 1970-01-01
    • 2023-04-07
    • 2020-01-15
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2012-11-08
    • 2013-07-28
    相关资源
    最近更新 更多