侧边栏壁纸
  • 累计撰写 278 篇文章
  • 累计创建 3 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

【QT】QT正则表达式

xuanxuan
2022-01-24 / 0 评论 / 0 点赞 / 2 阅读 / 2884 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-02-14,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

QT正则表达式

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

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

正则表达式中的量词

image-20220124111743871

正则表达式中的断言

image-20220124112005197

QRegExp支持通配符

image-20220124112047375

示例:

 //完整匹配
    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)$");//日期
    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$";
    QRegularExpression rDate1(sPattern);
    QString ss("Apr 01");
    QRegularExpressionMatch match2;
    match2 = rDate1.match(ss,0,QRegularExpression::PartialPreferCompleteMatch);    //部分匹配
    qDebug()<<match2.hasMatch();//完整匹配
    qDebug()<<match2.hasPartialMatch();//部分匹配
    qDebug()<<match2;
0

评论区