加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Qt之正则表达式 - QRegExp

发布时间:2020-12-14 02:20:05 所属栏目:百科 来源:网络整理
导读:作者:破砂锅 Qt里对大名鼎鼎的正则表达式有很好的支持,使用QRegExp类,你可以非常快的完成对文本的验证、数据提

作者:破砂锅

Qt里对大名鼎鼎的正则表达式有很好的支持,使用QRegExp类,你可以非常快的完成对文本的验证、数据提取、替换。Qt的SDK包里还提供了regexp的GUI小工具,方便你对正则表达式的验证。

本文在Qt4.5.3下验证通过。

用正则表达式验证文本有效性

你可以使用QRegExp::exactMatch来判断一个字符串是否符合一个pattern。

void testRegexMatch()
{
QString pattern(".*=.*");
QRegExp rx(pattern);
bool match = rx.exactMatch("a=3");
qDebug() << match; // True
match = rx.exactMatch("a/2");
qDebug() << match; // False
}

用正则表达式提取数据

你可以利用利用正则表达式从一个字符串里提取特定的字段或数据。例如,你可以用以下代码从"a=100"里提取"a"和"100"。

voidtestRegexCapture()
{
QStringpattern(
"(.*)=(.*)");
QRegExprx(pattern);

QStringstr(
"a=100");
intpos=str.indexOf(rx);//0,positionofthefirstmatch.
//Returns-1ifstrisnotfound.
//Youcanalsouserx.indexIn(str);
qDebug()<<pos;
if(pos>=0)
{
qDebug()
<<rx.matchedLength();//5,lengthofthelastmatchedstring
//or-1iftherewasnomatch
qDebug()<<rx.capturedTexts();//QStringList("a=100","a","100"),
//0:textmatchingpattern
//1:textcapturedbythe1st()
//2:textcapturedbythe2nd()

qDebug()
<<rx.cap(0);//a=100,textmatchingpattern
qDebug()<<rx.cap(1);//a,textcapturedbythenth()
qDebug()<<rx.cap(2);//100,

qDebug()
<<rx.pos(0);//0,positionofthenthcapturedtext
qDebug()<<rx.pos(1);//0
qDebug()<<rx.pos(2);//2
}
}

用正则表达式修改文本

你可以把字符串中匹配的字符串替换成"一般字符串"

QStrings="a=100";
s.replace(QRegExp(
"(.*)="),"b=");
qDebug()
<<s;//b=100

或是把字符串中匹配的字符串替换"提取的字符串"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读