正则表达式

正则表达式即一个文本匹配字符串的一种模式,Qt 中 QRegExp 类实现使用正则表达式进行模式匹配,且完全支持 Unicode,主要应用:字符串验证、搜索、查找替换、分割。正则表达式中字符及字符集

在这里插入图片描述
在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

代码

#include <QCoreApplication>
#include<QDebug>
#include<QRegularExpression>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QRegExp re("a");
    qDebug() << "匹配本身:"
             <<re.exactMatch("ab")//false
             <<re.exactMatch("a");//true

    QRegExp number("\\d*\\D{2}");//一个数字两个非数字
    qDebug() << "数字匹配"
             <<number.exactMatch("'13cm")//false
             <<number.exactMatch("1cm")//true
             <<number.exactMatch("2cew");//false

    QRegExp filetxt("*.txt");
    filetxt.setPatternSyntax(QRegExp::Wildcard);//支持通配符
    qDebug() << "通配符匹配"
             <<filetxt.exactMatch("main.txt")//true
             <<filetxt.exactMatch("main.txt.bak");//false

    QRegExp el;
    el.setPattern("\\b(hello|Hello)\\b");
    qDebug() << "匹配多个单词"
             <<el.indexIn("hellopig")//-1 匹配失败`
             <<el.indexIn("hi hello boy");//3 标识从3的位置开始0123

    //由(?:开始       )结束
    QRegExp regHeight("(\\d+)(?:\\s*)(cm|inch)");
    int res = regHeight.indexIn("jiang 222 cm");
    if(res > 1){
        qDebug() << regHeight.cap(0) //222 cm
                 << regHeight.cap(1) //222
                 << regHeight.cap(2);//cm
    }

    QRegExp reg;
    reg.setPattern("好(?!你)");
    QString ser = "你好啊,好啊你,好你个猪崽子";
    qDebug() << ser;
    ser.replace(reg,"嘻嘻");//好后面没有你改为嘻嘻
    qDebug() << ser;//你嘻嘻啊,嘻嘻啊你,好你个猪崽子

    //Qt5引入新类
    QRegularExpression regExp("hello");
    qDebug() << "QRegularExpression匹配字符"
             <<regExp.match("hello world");//0, 5, "hello":从第0到5个为hello

    regExp.setPattern("[A-Z]{3,8}");
    regExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
    qDebug() << "大小写不敏感匹配"
             << regExp.match("HELLO");//(0, 5, "HELLO")

    QRegularExpression regDate("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)$");
    QRegularExpressionMatch math = regDate.match("02/03/2023");
    if(math.hasMatch()){
         qDebug() << math.captured(0)//02/03/2023
                  << math.captured(1)//02
                  << math.captured(2)//03
                  << math.captured(3);//2023
    }

    QString sPatten = "(^(Jan|Feb|Mar|Apr|May)\\d\\d\\d\\d\\d\\d$)";
    QRegularExpression reDate1(sPatten);
    QString ss("Apr 01");
    QRegularExpressionMatch math2;
    math2 = reDate1.match(ss,
                          0,
                          QRegularExpression::PartialPreferCompleteMatch);
    qDebug() << math.hasMatch()//true
             <<math.hasPartialMatch();//false


               return a.exec();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值