天天看点

Qt正则表达式

作者:QT高级进阶

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

正则表达式中字符及字符集

Qt正则表达式

正则表达式中的量词

Qt正则表达式

正则表达式中的断言

Qt正则表达式

QRegExp支持通配符

Qt正则表达式

示例:

【领QT开发教程学习资料,点击→「链接」」←莬费领取,先码住不迷路~】

//完整匹配
    QRegExp reg("a");
    qDebug()<<reg.exactMatch("a");

    //任意个数字+两个非数字
    QRegExp reg0("\\d*\\D{2}");
    qDebug()<<reg0.exactMatch("123ab");

    //使用通配符匹配
    QRegExp rx("*.txt");
    //设置匹配语法
    rx.setPatternSyntax(QRegExp::Wildcard);//支持通配符
    qDebug()<<rx.exactMatch("123.txt");

    //匹配单词边界
    QRegExp reg1;
    //设置匹配模式
    reg1.setPattern("\\b(hello|Hello)\\b");
    qDebug()<<reg1.indexIn("Hello everyone.");//返回起始下标

    //捕获匹配的文本
    //由(?:开始。)结束
    QRegExp regHight("(\\d+)(?:\\s*)(cm|inchi)");
    qDebug()<<regHight.indexIn("Mr.WM 170cm");
    qDebug()<<regHight.cap(0);//完整
    qDebug()<<regHight.cap(1);//第一部分

    //断言?!
    QRegExp reg2;
    reg2.setPattern("面(?!包)");//面后面不是包才匹配成功
    QString str ="我爱吃面食,面包也行吧。";
    str.replace(reg2,"米");//我爱吃米食,面包也行吧
    qDebug()<<str;

    //Qt5引入了新的类
    QRegularExpression  regExp("hello");
    //结果QRegularExpressionMatch(Valid, has match: 0:(0, 5, "hello")
    qDebug()<<regExp.match("hello world");

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

    QRegularExpression reDate("^(\\d\\d)/(\\d\\d)/(\\d\\d\\d\\d)#34;);//日期
    QRegularExpressionMatch match0 = reDate.match("01/24/2022");
    QString strMatch = match0.captured(0);
    qDebug()<<strMatch;
    qDebug()<<match0;

    QString sPattern;
    sPattern = "^(Jan|Feb|Mar|Apr|May) \\d\\d \\d\\d\\d\\d#34;;
    QRegularExpression rDate1(sPattern);
    QString ss("Apr 01");
    QRegularExpressionMatch match2;
    match2 = rDate1.match(ss,0,QRegularExpression::PartialPreferCompleteMatch);    //部分匹配
    qDebug()<<match2.hasMatch();//完整匹配
    qDebug()<<match2.hasPartialMatch();//部分匹配
    qDebug()<<match2;           

继续阅读