Qt正则表达式运用---QRegExp

文章目录

1.匹配数字

1.1个位数

cpp 复制代码
    QString str= "0 1 2 23  10 20 ¥24 #0 @44 111 22- 123 58 99   ";
    QRegExp rx("\\b\\d{1}\\b");
    int index=0;
    while(rx.indexIn(str,index) != -1)
    {

        index = str.indexOf(rx.cap(),index) + rx.matchedLength();
        qDebug()<<rx.cap()<<"index="<<index<<"len"<<rx.matchedLength();

    }

执行结果

cpp 复制代码
"0" index= 1 len 1
"1" index= 3 len 1
"2" index= 5 len 1
"0" index= 12 len 1
"0" index= 15 len 1
"0" index= 22 len 1

这个方法有个弊端就是 10 20 这种两位数里面的0 也会被匹配出来,这个我也不知道是为什么?特殊情况特殊处理就行了。

但是如果是写成 QRegExp rx("^\\d{1}$");形式就可以精准匹配"0"."1","2","3"..."9"的字符串了,不会匹配"10"里面的0了。

1.2两位数 及多位数

cpp 复制代码
	str="0 1 2 23 01 10 20 ¥24 #0 @44 111 22- 123 58 99   "
    QRegExp rx("\\b\\d{2}\\b");

这个可以匹配两位数字

输出如下:

cpp 复制代码
"23" index= 8 len 2
"01" index= 11 len 2
"10" index= 14 len 2
"20" index= 17 len 2
"24" index= 21 len 2
"44" index= 28 len 2
"11" index= 31 len 2
"22" index= 35 len 2
"12" index= 39 len 2
"58" index= 43 len 2
"99" index= 46 len 2

如果想匹配出两位数10 -99 的数 可以这样写 QRegExp rx("\\b[1-9][0-9]\\b");

如果想匹配 1-99的数 可以写成QRegExp rx("\\b[1-9][0-9]?\\b");这个表示第一个数字是1到九之间的,第二个数字是零到九之间的,问号表示第二个数字可以有也可以没有。

如果想匹配出 10-999的数 :可以写成QRegExp rx("\\b[1-9]\\d\\d?\\b");这里的\d表示的就是[0-9]中的一个数

匹配多位数 QRegExp rx("\\b[1-9]\\d{n}\\b");n=1:匹配两位数,n=2:匹配三位数,n=3:匹配四位数。

1.3 匹配非数字

cpp 复制代码
QString str= "0 1 2 23  10 20 ¥24 #0 @44 111 22- 123 58 99   ";
QRegExp rx1("[^0-9]");
QRegExp rx2("[^0-9|\\s]");

rx1就可以匹配出非数字的符号,[^0-9]:表示不匹配0-9的数字。rx2可以匹配出除了数字和空格以外的字符。

匹配单词

cpp 复制代码
QString str = "Hello world! This is a sample text.";
QRegExp rx("\\b\\w+\\b");
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
    qDebug() << rx.cap(0);
    pos += rx.matchedLength();
}

输出

cpp 复制代码
"Hello"
"world"
"This"
"is"
"a"
"sample"
"text"

用法都差不多,主要是具体情况具体处理,后续再完善...

相关推荐
胖咕噜的稞达鸭26 分钟前
C++技术岗面试经验总结
开发语言·网络·c++·网络协议·tcp/ip·面试
众创岛1 小时前
iframe的属性获取
开发语言·javascript·ecmascript
一个处女座的程序猿O(∩_∩)O1 小时前
Python基础知识大全:从零开始掌握Python核心语法
开发语言·python
小陈工1 小时前
Python Web开发入门(十一):RESTful API设计原则与最佳实践——让你的API既优雅又好用
开发语言·前端·人工智能·后端·python·安全·restful
计算机安禾1 小时前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio
csbysj20202 小时前
网站主机技术概述
开发语言
FL16238631292 小时前
基于yolov26+pyqt5的混凝土墙面缺陷检测系统python源码+pytorch模型+评估指标曲线+精美GUI界面
python·qt·yolo
froginwe112 小时前
jQuery 事件方法详解
开发语言
echome8882 小时前
JavaScript Promise 与 async/await 实战:5 个高频异步编程场景的优雅解决方案
开发语言·javascript·ecmascript
道清茗3 小时前
【MySQL知识点问答题】高级复制技术
数据库·mysql