QT正则表达式

 通配符:*

    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值