QT正则表达式

正则表达式即一个文本匹配字符串的一种模式。Qt中QRegExp类实现使用正则表达式进行模式匹配,且完全支持Unicode,主要应用:字符串验证、搜索、查找替换、分割。

正则表达式中字符及字符集

正则表达式中的量词

image-20220124111743871

正则表达式中的断言

image-20220124112005197

QRegExp支持通配符

image-20220124112047375

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//完整匹配
QRegExp reg("a");
qDebug()<<reg.exactMatch("a");

//任意个数字+两个非数字
QRegExp reg0("\\d*\\D{2}");
qDebug()<<reg0.exactMatch("123ab");

//使用通配符匹配
QRegExp rx("*.txt");
//设置匹配语法
rx.setPatternSyntax(QRegExp::Wildcard);//支持通配符
qDebug()<<rx.exactMatch("123.txt");

//匹配单词边界
QRegExp reg1;
//设置匹配模式
reg1.setPattern("\\b(hello|Hello)\\b");
qDebug()<<reg1.indexIn("Hello everyone.");//返回起始下标

//捕获匹配的文本
//由(?:开始。)结束
QRegExp regHight("(\\d+)(?:\\s*)(cm|inchi)");
qDebug()<<regHight.indexIn("Mr.WM 170cm");
qDebug()<<regHight.cap(0);//完整
qDebug()<<regHight.cap(1);//第一部分

//断言?!
QRegExp reg2;
reg2.setPattern("面(?!包)");//面后面不是包才匹配成功
QString str ="我爱吃面食,面包也行吧。";
str.replace(reg2,"米");//我爱吃米食,面包也行吧
qDebug()<<str;

//Qt5引入了新的类
QRegularExpression regExp("hello");
//结果QRegularExpressionMatch(Valid, has match: 0:(0, 5, "hello")
qDebug()<<regExp.match("hello world");

regExp.setPattern("[A-Z]{3,8}");
//设置匹配模式-大小写不敏感
regExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
qDebug()<<regExp.match("hello");

QRegularExpression reDate("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)$");//日期
QRegularExpressionMatch match0 = reDate.match("01/24/2022");
QString strMatch = match0.captured(0);
qDebug()<<strMatch;
qDebug()<<match0;

QString sPattern;
sPattern = "^(Jan|Feb|Mar|Apr|May) \\d\\d \\d\\d\\d\\d$";
QRegularExpression rDate1(sPattern);
QString ss("Apr 01");
QRegularExpressionMatch match2;
match2 = rDate1.match(ss,0,QRegularExpression::PartialPreferCompleteMatch); //部分匹配
qDebug()<<match2.hasMatch();//完整匹配
qDebug()<<match2.hasPartialMatch();//部分匹配
qDebug()<<match2;