0

I'm stuck with this. I am trying to tokenize a multiline QString and count the number of lines.

QStringList sentences = m_text.split(QRegularExpression("\n|$"), Qt::SkipEmptyParts);
qDebug() << sentences.size();

In spite of the Qt::SkipEmptyParts behaviour, I keep getting 1 for a string like this, which should report 5:

Hello\n\n\n\n\n

Any Idea of what's wrong.

By the way, if the string has something at the end the count works fine:

Hello\n\n\n\n\nBye

reports 6 sentences.

coterobarros
  • 941
  • 1
  • 16
  • 25
  • 2
    Documentation for [`Qt::SkipEmptyParts`](https://doc.qt.io/qt-6/qt.html#SplitBehaviorFlags-enum): *If a field is empty, **don't** include it in the result.* 1 is therefore the expected result. As to the `6` you get in your second test, I believe you have not tested correctly: your string has 5 `\n` that go between 6 strings (if you where to use `Qt::KeepEmptyParts`) but the additional `$` from your regular expression creates 1 last empty string. Had you properly tested, you would have gotten either `2` (with `SkipEmptyParts`) or `7` (with `KeepEmptyParts)` for the result but not `6`. – Atmo May 24 '23 at 13:47
  • My fault! I though I had `Qt::KeepEmptyParts` in my code. Sorry for the mistake – coterobarros May 24 '23 at 14:46

0 Answers0