Qt5.0 正则表达式 QRegularExpression 的使用

  QRegularExpression 是Qt 5.0才引进的,相对于QRegExp,QRegularExpression class修复了很多bug,提高了效率,提供了对Perl的RegEx几乎全面兼容的搜索引擎。简单说,QRegExp年久失修,bug较多,使用时建议使用QRegularExpression。

先上代码,后面逐函数简介:

    QRegularExpression regularExpression(pattern);
    int index = 0;
    QRegularExpressionMatch match;
    do {
        match = regularExpression.match(testStr, index);
        if(match.hasMatch()) {
            index = match.capturedEnd();
            qDebug()<<"("<<match.capturedStart() <<","<<index<<") "<<match.captured(0);
        }
        else
           break; 
    } while(index < testStr.length());

一、与QRegExp 的主要用法区别

QRegExp 的匹配结果存放在QRegExp对象自身:
QString QRegExp::cap(int nth = 0) const;
而QRegularExpression 类只用来检索匹配,把检索结果单列出来,成为一个类QRegularExpressionMatch;
QString QRegularExpressionMatch::captured(int nth = 0) const;
推测:这样以来,QRegularExpression 检索的负担减小,效率因此提高;

二、函数介绍

1.match() 匹配:

    QRegularExpressionMatch match(const QString &subject,
                                  int offset                = 0,
                                  MatchType matchType       = NormalMatch,
                                  MatchOptions matchOptions = NoMatchOption) const;

subject  被匹配的目标字符串;

offset 偏移,匹配起始位置;

MatchType 匹配类型;

MatchOption匹配选项;

返回值 匹配的结果对象;

2. 匹配主要结果:

QString captured(int nth = 0) const;
int capturedStart(int nth = 0) const;
int capturedLength(int nth = 0) const;
int capturedEnd(int nth = 0) const;

分别为匹配到的字符串,匹配字符串的起点,长度,终点;

注意:都带参数,意味着可以获取每个匹配段(即为正则表达式中的每个括号)的字符串及其长度和起终点。

captured() 函数与 QRegExp::cap() 基本一致,不过相比增加了三个函数,返回每个匹配段的位置;

例如正则pattern为 "(\\w+)(\\d+)"

match.captured() 获取正则匹配结果,缺省参数为0;

match.captured(1) 获取(\\w+) 对应匹配结果,返回的是字母;

match.capturedStart(1) 获取这段字母在整个字符串的起始位置;

match.captured(2) 获取(\\d+) 对应匹配结果,返回的是数字;

match.capturedEnd(2) 获取这段字母在整个字符串的结束位置;

3. captureEnd()

int QRegularExpressionMatch::capturedEnd(int nth = 0) const;
QRegExp匹配遍历,只能获得匹配的字符串长度和匹配位置。下个循环的匹配起点需要手动处理(相加):
int pos = 0;
while ((pos = rx.indexIn(trl , pos)) != -1)
{
    pos += rx.matchedLength();
    qDebug() << rx.cap();
}

现在QRegularExpression可以用match.captureEnd()返回值直接作为下次遍历的起始检索位置;

4.capturedTexts()

QStringList capturedTexts() const;
返回各个匹配段的QStringList,其按照在Patern中的顺序。

即captured(1),captured(2),captured(3),,,等所有匹配段结果的QStringList。

5.lastCapturedIndex()

最后一个匹配段的索引,亦即所有匹配段的数量;

QRegularExpressionMatch match = re.match(string);
for (int i = 0; i <= match.lastCapturedIndex(); ++i) {
      QString captured = match.captured(i);
      // ...
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值