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"

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

相关推荐
SomeOtherTime4 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood4 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青5 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
饮水桶_T9 小时前
JAVA IO流笔记
开发语言·数据结构·算法
Felven11 小时前
C. Brr Brrr Patapim
c语言·开发语言
星恒随风11 小时前
MySQL 从零入门(四):表的增删改查与基础查询详解
linux·服务器·数据库·笔记·mysql
路溪非溪12 小时前
python标准库使用总结
开发语言·python
Pniubi13 小时前
MySQL靠什么实现事务的?事务隔离级别有哪些?
java·数据库·mysql
aiks_yuan14 小时前
MySQL 死锁怎么排查:看懂 INNODB STATUS 死锁日志,先查后插为什么必死锁(MySQL 8.2 实测)
mysql
SomeOtherTime14 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust