如何在拆分QString时转义分隔符

How to escape the delimiter when splitting a QString?

本文关键字:转义 分隔符 QString 拆分      更新时间:2023-10-16

如何用字符(例如:'+')拆分QString,并且在转义该字符时不拆分:'+'

谢谢!

根据要求,提供更多细节:

要拆分的字符串:"a++"

分隔符:'+'

所需输出:"a""+"

您需要将globalMatch与一个正则表达式一起使用以进行拆分,该表达式选择除非转义'+':之外的所有内容

(?:[^\+]|\.)*

实时示例

因此,给定QString foo,您可以使用QRegularExpressionMatchIterator:迭代列表

QRegularExpression bar("((?:[^\\\+]|\\.)*)");
auto it = bar.globalMatch(foo);
while(it.hasNext()){
    cout << it.next().captured(1).toStdString() << endl;
}

在C++11中,您还可以使用cregex_token_iterator:

regex bar("((?:[^\\\+]|\\.)+)");
copy(cregex_token_iterator(foo.cbegin(), foo.cend(), bar, 1), cregex_token_iterator(), ostream_iterator<string>(cout, "n"));

实时检查


不幸的是,您既没有Qt5,也没有C++11,也没有Boost,您可以使用QRegExp:

QRegExp bar("((?:[^\\\+]|\\.)*)");
for(int it = bar.indexIn(foo, 0); it >= 0; it = bar.indexIn(foo, it)) {
    cout << bar.cap(1).toStdString() << endl;
}

如果不使用"+"作为分隔符,而是使用空格作为分隔符。。。splitArgs为您工作:

https://stackoverflow.com/a/48977326/2660408