Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
我想清理QString数据以具有以下内容:

输入

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


输出

normal, here's double phrased


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

另外,我正在使用Qt 4,因此这需要由QRegExp完成。

最佳答案

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的原始灵感。

关于c++ - 在双括号QString之间仅选择一个选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19017600/

10-11 22:42
查看更多