QRegExp 已被淘汰不建议使用
头文件:
#include <QRegularExpression> #include <QRegularExpressionMatch>
注意匹配中文要用 QRegularExpression re("([\u4e00-\u9fa5]+)"); 不能用 QRegularExpression re(R"__(([\u4e00-\u9fa5]+))__");
全局匹配:
QRegularExpression re(preg);//表达式 QRegularExpressionMatchIterator iter = re.globalMatch(webStr);//全局匹配 //使用迭代器遍历匹配 while (iter.hasNext()) { QRegularExpressionMatch match = iter.next(); qDebug() << "第1个子项目" << match.captured(1); }
//匹配一次 match ,性能很好
QRegularExpression re("\\d{3}([a-z]+|[A-Z]+)"); QRegularExpressionMatch match=re.match(html);//匹配结果 if(match.hasMatch()){ qDebug() << "第1个子项目" << match.captured(1); }
正则替换:
//替换字符串 QString newF = txtFname.replace(QRegular_Expression(R"__((\.[a-z]{3,4}))__"), R"__(_替换\1)__");
附加选项:
QString preg = "([\\w\u4e00-\u9fa5]+)";//正则匹配中文和数字字母下划线 - 注意如果要匹配中文不能放在R原始字符串里边,否则\u无法转义 QRegularExpression re(preg );//创建正则对象 re.setPatternOptions(QRegularExpression::MultilineOption);// (^) 和 ($) 之间允许换行 re.setPatternOptions(QRegularExpression::CaseInsensitiveOption);//不区分大小写 re.setPatternOptions(QRegularExpression::UseUnicodePropertiesOption);//支持unicode,匹配中文需要设置这个属性 match.capturedEnd(1) //匹配字符串组的开始位置 match.capturedStart(1)//结束位置