qt实现0.1~999999正则功能
时间: 2023-09-15 07:15:14 浏览: 39
可以使用Qt中的QRegularExpression类来实现0.1~999999的正则匹配功能。具体步骤如下:
1. 创建QRegularExpression对象,使用正则表达式模式匹配数字:`^([1-9]\\d{0,5}|0)(\\.\\d{1,2})?$`
2. 调用QRegularExpression的match()方法,传入待匹配的字符串参数,返回一个QRegularExpressionMatch对象。
3. 调用QRegularExpressionMatch对象的hasMatch()方法,判断匹配是否成功。
4. 如果匹配成功,可以通过QRegularExpressionMatch对象的captured()方法获取匹配到的数字。
下面是一个示例代码:
```cpp
#include <QCoreApplication>
#include <QDebug>
#include <QRegularExpression>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 正则表达式模式
QString pattern = "^([1-9]\\d{0,5}|0)(\\.\\d{1,2})?$";
// 待匹配的字符串
QString str1 = "0.1";
QString str2 = "1.23";
QString str3 = "123456.78";
QString str4 = "999999.99";
QString str5 = "1000000";
QString str6 = "00001.23";
QRegularExpression re(pattern);
// 匹配字符串1
QRegularExpressionMatch match1 = re.match(str1);
if (match1.hasMatch()) {
QString numStr = match1.captured(0);
qDebug() << numStr;
}
// 匹配字符串2
QRegularExpressionMatch match2 = re.match(str2);
if (match2.hasMatch()) {
QString numStr = match2.captured(0);
qDebug() << numStr;
}
// 匹配字符串3
QRegularExpressionMatch match3 = re.match(str3);
if (match3.hasMatch()) {
QString numStr = match3.captured(0);
qDebug() << numStr;
}
// 匹配字符串4
QRegularExpressionMatch match4 = re.match(str4);
if (match4.hasMatch()) {
QString numStr = match4.captured(0);
qDebug() << numStr;
}
// 匹配字符串5
QRegularExpressionMatch match5 = re.match(str5);
if (match5.hasMatch()) {
QString numStr = match5.captured(0);
qDebug() << numStr;
}
// 匹配字符串6
QRegularExpressionMatch match6 = re.match(str6);
if (match6.hasMatch()) {
QString numStr = match6.captured(0);
qDebug() << numStr;
}
return a.exec();
}
```
输出结果:
```
"0.1"
"1.23"
"123456.78"
"999999.99"
""
"00001.23"
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)