通配符:*
QRegExp reg("*.txt");
reg.setPatternSyntax(QRegExp::Wildcard);//支持通配符,不设置的话false
qDebug()<<reg.exactMatch("eeeeeeeeee.txt")<<reg.exactMatch(" eee.txt.bat");
匹配单词边界:\b
QRegExp reg;
reg.setPattern("\\b(hello|Hello)\\b");
qDebug()<<reg.indexIn("helloEveryone")//-1表失败
<<reg.indexIn("Hmm hello everypne");//4,匹配到的位置
捕获匹配的文本
匹配后捕获的结果按照小括号分组,小括号加?:为非捕获,即不会捕获该分组
QRegExp reg("(\\d+)(?:\\s*)(cm|inch)");
int res = reg.indexIn("YaoMing 226 cm");//是否得到匹配
if(res > -1){
qDebug()<<reg.cap(0)<<"cap(1)"<<reg.cap(1)<<"cap(2)"<<reg.cap(2);
}
断言?!:不紧跟才匹配
?=:紧跟才匹配
QRegExp reg;
reg.setPattern("面(?!包)");
QString str = "面没了,吃面包也好,吃面食也好";
qDebug()<<str<<endl;
str.replace(reg,"意大利");
qDebug()<<str<<endl;
"面没了,吃面包也好,吃面食也好"
"意大利没了,吃面包也好,吃意大利食也好"
QT5引入了新的类
匹配信息更加详细
QRegularExpression reg("hello");
qDebug()<<reg.match("hello world!");
输出:
QRegularExpressionMatch(Valid, has match: 0:(0, 5, "hello"))
设置大小写不敏感和分组捕获与QRegExp类似
QRegularExpression reg("hello");
//reg.setPattern("[A-Z]{3,8}");
reg.setPatternOptions(QRegularExpression::CaseInsensitiveOption);//设置大小写不敏感
qDebug()<<reg.match("HELLoworld!");
QRegularExpression reDate("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)$");
QRegularExpressionMatch match0 = reDate.match("01/06/2000");//match类
qDebug()<<match0.captured(0)<<endl;//捕获到的完整字符串
qDebug()<<match0.captured(1)<<endl;//从1开始算分组
qDebug()<<match0.captured(2)<<endl;
qDebug()<<match0.captured(3)<<endl;
输出:
QRegularExpressionMatch(Valid, has match: 0:(0, 5, "HELLo"))
"01/06/2000"
"01"
"06"
"2000"
部分匹配
QString sPattern;
sPattern = "^(Jan|Feb|Mar|Apr|May) \\d\\d \\d\\d\\d\\d$";
QRegularExpression reDate(sPattern);
QString ss("Apr 01");
//部分匹配
QRegularExpressionMatch match = reDate.match(ss,0,QRegularExpression::PartialPreferCompleteMatch);
qDebug()<<match.hasPartialMatch();
qDebug()<<match.hasMatch();
输出
true
false