QT正则表达式
正则表达式即一个文本匹配字符串的一种模式。Qt中QRegExp类实现使用正则表达式进行模式匹配,且完全支持Unicode,主要应用:字符串验证、搜索、查找替换、分割。
正则表达式中字符及字符集
![](https://gitee.com/Do2eM0N/blogimg/raw/master/202201241110136.png)
正则表达式中的量词
![image-20220124111743871](https://gitee.com/Do2eM0N/blogimg/raw/master/202201241655096.png)
正则表达式中的断言
![image-20220124112005197](https://gitee.com/Do2eM0N/blogimg/raw/master/202201241120248.png)
QRegExp支持通配符
![image-20220124112047375](https://gitee.com/Do2eM0N/blogimg/raw/master/202201241120415.png)
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| 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;
QRegularExpression regExp("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;
|