我想从包含空格和常用的QString中提取数字,我的代码就像这样:
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")
正如您所看到的,当空格位于字符串处时,前方会出现意外的""
。开始。
所以我的问题很简单:如何编辑正则表达式以删除前面的空格或常见的?
提前感谢您的回答!
答案 0 :(得分:2)
嗯,您的代码已经匹配字符串开头的空格。这些是匹配:
“ 3
,
50 ,
200 , \t\t
100 ,
70 ,
+ 3 ,
5”
您需要了解QString::split()的工作原理:
注意,您还需要注意字符串 end 的匹配项:
QString line = "1, 2 \t 3 4 ";
QStringList strList = line.split(QRegularExpression("[,\\s]+"));
// Result: ["1", "2", "3", "4", ""]
您要求QString :: split()通过传递QString::SkipEmptyParts
标志从结果中排除空字符串。
仅通过更改QRegularExpression就无法做到这一点。您可以排除空字符串,也可以手动删除不需要的字符。
您可以要求QString :: split()排除空字符串...
QStringList strList = line.split(QRegularExpression("[,\\s]+"), QString::SkipEmptyParts)
...或者在拆分之前从字符串的开头/结尾删除空格(QString::trimmed()就是这样)...
QStringList strList = line.trimmed().split(QRegularExpression("[,\\s]+"))
...或者在拆分之前从字符串的开头/结尾删除空格和逗号
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]+"))