在 spaces 上拆分 QString 并在 QList 中保留 space - 最好或 'canonical' 方式

Splitting QString on spaces and keeping the space in QList - best or 'canonical' way

如标题所示,我想问一下在空格上拆分 QString 的最佳方法是什么,并且 - 在相关的情况下 - 将空格保留为生成的 QList 元素的一部分。考虑到现代 C++ 和 Qt >= 6.0 范例,我对最有效的方法很感兴趣。

为了这个问题的目的,我将用'_'替换普通空格 - 我希望它能让问题更容易理解。

想象一下下面的代码:

QString myString = "This_is_an_exemplary_text";
for (auto word : myString.split('_')) {
   qDebug() << word;
}

代码的输出为:

"This" "is" "an" "exemplary" "text"

有关空间的信息在拆分过程中丢失了。有没有一种聪明的方法来保存它,并有以下输出:

"This_" "is_" "an_" "exemplary_" "text"

欢迎任何建议。

考虑 myString.split(QRegularExpression("(?<= )") 正则表达式使用正 look-behind 语法表示“空子字符串前面有 space”。