正则表达式即一个文本匹配字符串的一种模式,Qt 中 QRegExp 类实现使用正则表达式进行模式匹配,且完全支持 Unicode,主要应用:字符串验证、搜索、查找替换、分割。正则表达式中字符及字符集
代码
#include <QCoreApplication>
#include<QDebug>
#include<QRegularExpression>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QRegExp re("a");
qDebug() << "匹配本身:"
<<re.exactMatch("ab")//false
<<re.exactMatch("a");//true
QRegExp number("\\d*\\D{2}");//一个数字两个非数字
qDebug() << "数字匹配"
<<number.exactMatch("'13cm")//false
<<number.exactMatch("1cm")//true
<<number.exactMatch("2cew");//false
QRegExp filetxt("*.txt");
filetxt.setPatternSyntax(QRegExp::Wildcard);//支持通配符
qDebug() << "通配符匹配"
<<filetxt.exactMatch("main.txt")//true
<<filetxt.exactMatch("main.txt.bak");//false
QRegExp el;
el.setPattern("\\b(hello|Hello)\\b");
qDebug() << "匹配多个单词"
<<el.indexIn("hellopig")//-1 匹配失败`
<<el.indexIn("hi hello boy");//3 标识从3的位置开始0123
//由(?:开始 )结束
QRegExp regHeight("(\\d+)(?:\\s*)(cm|inch)");
int res = regHeight.indexIn("jiang 222 cm");
if(res > 1){
qDebug() << regHeight.cap(0) //222 cm
<< regHeight.cap(1) //222
<< regHeight.cap(2);//cm
}
QRegExp reg;
reg.setPattern("好(?!你)");
QString ser = "你好啊,好啊你,好你个猪崽子";
qDebug() << ser;
ser.replace(reg,"嘻嘻");//好后面没有你改为嘻嘻
qDebug() << ser;//你嘻嘻啊,嘻嘻啊你,好你个猪崽子
//Qt5引入新类
QRegularExpression regExp("hello");
qDebug() << "QRegularExpression匹配字符"
<<regExp.match("hello world");//0, 5, "hello":从第0到5个为hello
regExp.setPattern("[A-Z]{3,8}");
regExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
qDebug() << "大小写不敏感匹配"
<< regExp.match("HELLO");//(0, 5, "HELLO")
QRegularExpression regDate("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)$");
QRegularExpressionMatch math = regDate.match("02/03/2023");
if(math.hasMatch()){
qDebug() << math.captured(0)//02/03/2023
<< math.captured(1)//02
<< math.captured(2)//03
<< math.captured(3);//2023
}
QString sPatten = "(^(Jan|Feb|Mar|Apr|May)\\d\\d\\d\\d\\d\\d$)";
QRegularExpression reDate1(sPatten);
QString ss("Apr 01");
QRegularExpressionMatch math2;
math2 = reDate1.match(ss,
0,
QRegularExpression::PartialPreferCompleteMatch);
qDebug() << math.hasMatch()//true
<<math.hasPartialMatch();//false
return a.exec();
}