Reputation: 406
I would like to extract digits from a QString containing space and common, and my code just like this:
QString line = " 3 , 50, 200, \t\t100, 70, +3, 5";
QStringList strList = line.split(QRegularExpression("[,\\s]+"));
qDebug() << strList;
// what I expect
// ("3", "50", "200", "100", "70", "+3", "5")
// while the result is
// ("", "3", "50", "200", "100", "70", "+3", "5")
As you can see, there is an unexpected ""
ahead when spaces are at the strings' beginning.
So my question is simple: how to edit the regular expression to remove the front spaces or common?
Thank you for your answers in advance!
Upvotes: 0
Views: 1749
Reputation: 2718
Well, your code already matches the space at the beginning of the string. These are the matches:
"3
,
50,
200, \t\t
100,
70,
+3,
5"
You need to understand how QString::split() works:
Note, you also need to watch out for matches at the end of your string:
QString line = "1, 2 \t 3 4 ";
QStringList strList = line.split(QRegularExpression("[,\\s]+"));
// Result: ["1", "2", "3", "4", ""]
You ask QString::split() to exclude the empty strings from your result, by passing the QString::SkipEmptyParts
flag.
You cannot do this just by changing your QRegularExpression. You can exclude the empty strings, or remove the unwanted characters manually.
You can ask QString::split() to exclude the empty strings...
QStringList strList = line.split(QRegularExpression("[,\\s]+"), QString::SkipEmptyParts)
...or remove spaces from the start/end of the string before splitting (QString::trimmed() does exactly that)...
QStringList strList = line.trimmed().split(QRegularExpression("[,\\s]+"))
...or remove spaces and commas from the start/end of the string before splitting
line.remove( QRegularExpression("^[,\\s]+") ); // Remove spaces and commas at the start of the string
line.remove( QRegularExpression("[,\\s]+$") ); // Remove spaces and commas at the end of the string
QStringList strList = line.split(QRegularExpression("[,\\s]+"))
Upvotes: 2