Qt 正则表达式 用QRegularExpression代替QRegExp
发布时间:2020-12-14 04:19:29 所属栏目:百科 来源:网络整理
导读:QRegularExpression 是Qt 5.0才引进的,相对于QRegExp,QRegularExpression class修复了很多bug,提高了效率,提供了对Perl的RegEx几乎全面兼容的搜索引擎。简单说,QRegExp年久失修,bug较多,使用时建议使用QRegularExpression。 注意:若在正则表达式中需
QRegularExpression 是Qt 5.0才引进的,相对于QRegExp,QRegularExpression class修复了很多bug,提高了效率,提供了对Perl的RegEx几乎全面兼容的搜索引擎。简单说,QRegExp年久失修,bug较多,使用时建议使用QRegularExpression。 #include <QCoreApplication>
#include <QDebug>
#include <QRegExp>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
int main(int argc,char *argv[])
{
QString pattern1 = ".*=d*";
QString pattern2 = "[a-z]*=d*";
QString pattern3 = "w+";
QString pattern4 = "(.+)=(.+)";
QString test1("a=123");
QString test2("-rna=123abc");
QString test3("-_%rna=1abc-_%rna=12abc-_%rna=123abc-_%rna=1234abc");
QString test4("hello world,hello qt");
//test="a=123",pattern=".*=d*"
QRegExp regExp(pattern1);
qDebug()<<regExp.exactMatch(test1);//true
//test="a=-rna=123abc",pattern="[a-z]*=d*"
regExp.setPattern(pattern1);
int pos = test2.indexOf(regExp);
int matchedLen = regExp.matchedLength();
QStringList capTexts = regExp.capturedTexts();
qDebug()<<pos<<","<<matchedLen<<","<<capTexts;//0,8,("-rna-123")
//test="-_%rna=1abc-_%rna=12abc-_%rna=123abc-_%rna=1234abc",pattern="[a-z]*=d*"
regExp.setPattern(pattern2);
//只会找到第一个就停止了
pos = test3.indexOf(regExp);
matchedLen = regExp.matchedLength();
capTexts = regExp.capturedTexts();
qDebug()<<pos<<","<<capTexts.length()<<","<<capTexts;//5,3,1,("a=1")
//test="-_%rna=1abc-_%rna=12abc-_%rna=123abc-_%rna=1234abc",pattern="[a-z]*=d*"
regExp.setPattern(pattern2);
//替换所有,并返回该字符串的引用
qDebug()<<test3.replace(regExp,"xyz");//-_%rnxyzabc-_%rnxyzabc-_%rnxyzabc-_%rnxyzabc"
qDebug()<<test3;//-_%rnxyzabc-_%rnxyzabc-_%rnxyzabc-_%rnxyzabc"
//////////////////////////////////////////////////////////////////////////////////////////////////////
//test="hello world,hello qt",pattern="w+"
//Since: Qt 5.0
QRegularExpression regularExpression(pattern3);
int index = 0;
QRegularExpressionMatch match;
do {
match = regularExpression.match(test4,index);
if(match.hasMatch()) {
index = match.capturedEnd();
qDebug()<<"("<<match.capturedStart()<<","<<index<<") "<<match.captured(0);
//(0,5) "hello"
//(6,11) "world"
//(13,18) "hello"
//(19,21) "qt"
} else {
break;
}
} while(index < test4.length());
//test="a=-rna=123abc",pattern="w+"
qDebug()<<test2.indexOf(regularExpression);//3
//test="hello world,pattern="w+"
qDebug()<<test4.replace(regularExpression,"x");//"x x,x x"
//正则表达式分组
//test="a=123",pattern="(.+)=(.+)"
regularExpression.setPattern(pattern4);
match = regularExpression.match(test1);
qDebug()<<match.captured(0);//"a=123"
qDebug()<<match.captured(1);//"a"
qDebug()<<match.captured(2);//"123"
qDebug()<<match.capturedTexts();//("a=100","a","100")
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |