首先有这样的一个需求,去掉QString字符串中所有的空格,空白符\n和\t,那我们该怎么快速实现呢?
这个需求的一个应用场景就是,你可以把没有空格的字符串当做key,存放到map或者其他容器中。
正则表达式中\s匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
\f -> 匹配一个换页
\n -> 匹配一个换行符
\r -> 匹配一个回车符
\t -> 匹配一个制表符
\v -> 匹配一个垂直制表符
而“\s+”则表示匹配任意多个上面的字符。另因为反斜杠在C++里是转义字符,所以在C++里,我们要这么用“\s+”.
那么问题来了,“\s+”有啥使用场景呢?
QString &QString::remove(const QRegExp &rx)
Removes every occurrence of the regular expression rx in the string, and returns a reference to the string. For example:
所有用正则匹配到的,都会被QString.remove删掉,所以这里用"\s"还是"\s+"都是可以的,不信你可以试试
QString strSrc = "hello\t \t \n worl d";
qDebug() << strSrc;
qDebug() << strSrc.remove(QRegExp("\\s"));
qDebug() << strSrc.remove(QRegExp("\\s+"));
运行结果:
"hello\t \t \n worl d"
"helloworld"
"helloworld"
另外,Qt的正则表达式出了新款——QRegularExpression
也是一样的用法,唯一不同的是需要手动包含头文件
#include <QRegularExpression>
QString strSrc = "hello\t \t \n worl d";
qDebug() << strSrc;
qDebug() << strSrc.remove(QRegularExpression("\\s"));
运行结果:
"helloworld"
参考:
非常好用的正则表达式"\s+"