# Qt:正则表达式判断字符串是否为数值
记录一下,利用正则表达式判断字符串是否为数值(匹配是否为整数,浮点数或者科学计数法数值)
参考博客
#include <QString>
#include <QDebug>
#include <iostream>
#include <QRegExp>
static bool isNumeric(QString str) {
if (str.size()==0) {
return false;
}
QRegExp regx("[+-]*\\d+\\.?\\d*[Ee]*[+-]*\\d+");
bool isNumber = regx.exactMatch(str.trimmed());
if (isNumber) {
return isNumber;
}
regx.setPattern("^[-\\+]?[.\\d]*$");
return regx.exactMatch(str.trimmed());
}
int main(){
QStringList strs={"1E8"," -9.81 ","-9.81A","-A9.81","1.025e3"};
for(auto str:strs){
qDebug()<<str<<" "<<isNumeric(str)<<QString(str).toDouble();
}
return 0;
}
输出:
"1E8" true 1e+08
" -9.81 " true -9.81
"-9.81A" false 0
"-A9.81" false 0
"1.025e3" true 1025