QRegularExpression 是Qt 5.0才引进的,相对于QRegExp,QRegularExpression class修复了很多bug,提高了效率,提供了对Perl的RegEx几乎全面兼容的搜索引擎。简单说,QRegExp年久失修,bug较多,使用时建议使用QRegularExpression。
注意:若在正则表达式中需要用到”\”,需要在它前面补一个转义字符”\”,因为”\”在字符串中是一个转义字符会将后面的字符换算成ASCII码进行转义。所以如果要将”\”传递到正则当中就需要多添加一个”\”做转义。
#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("-\r\na=123abc");
QString test3("-_%\r\na=1abc-_%\r\na=12abc-_%\r\na=123abc-_%\r\na=1234abc");
QString test4("hello world,hello qt");
//test="a=123",pattern=".*=\\d*"
QRegExp regExp(pattern1);
qDebug()<<regExp.exactMatch(test1);//true
//test="a=-\r\na=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,("-\r\na-123")
//test="-_%\r\na=1abc-_%\r\na=12abc-_%\r\na=123abc-_%\r\na=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="-_%\r\na=1abc-_%\r\na=12abc-_%\r\na=123abc-_%\r\na=1234abc",pattern="[a-z]*=\\d*"
regExp.setPattern(pattern2);
//替换所有,并返回该字符串的引用
qDebug()<<test3.replace(regExp,"xyz");//-_%\r\nxyzabc-_%\r\nxyzabc-_%\r\nxyzabc-_%\r\nxyzabc"
qDebug()<<test3;//-_%\r\nxyzabc-_%\r\nxyzabc-_%\r\nxyzabc-_%\r\nxyzabc"
//////////////////////////////////////////////////////////////////////////////////////////////////////
//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=-\r\na=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;
}