您的位置:首页 > 编程语言 > Qt开发

Qt中使用正则表达式返回匹配的所有结果集

2013-04-11 23:15 507 查看
Python的正则中有findAll函数返回一个所有匹配的结果list.

今天在使用Qt的时候发现似乎没有类似的方法.进而自己写了一个, 代码如下

/**

*@brief获取所有的匹配结果

*@paramtext要匹配的文本

**@paramregexp正则表达式串

*@return匹配的结果集

*/

QSet<QString>UploadBase::getAllMatchResults(constQStringtext,constQStringregexp)

{

QSet<QString>resultSet;


QRegExprx(regexp);

intpos=0;


while((pos=rx.indexIn(text,pos))!=-1)

{

pos+=rx.matchedLength();

QStringresult=rx.cap(0);

resultSet<<result;

}


returnresultSet;

}


测试:

假如在如下的test.h 要获取所有include的文件名

//test.h

#include <Metro.h>
#include <FreeSixIMU.h>
#include <FIMU_ADXL345.h>
#include <FIMU_ITG3200.h>
#include <Wire.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremote.h>


可以这么使用

QSet<QString>libReference;

QFilefile(filePath);//filePath是test.h的路径

if(!file.open(QFile::ReadOnly))

{

qDebug()<<file.errorString();

returnlibReference;//returnaemptyobject

}


QStringcode=file.readAll();


libReference=getAllMatchResults(code,"\\w+\\.h");


libReference中的结果为 Metro.h, FreeSixIMU.h, FIMU_ADXL345.h, FIMU_ITG3200.h, Wire.h, LiquidCrystal_I2C.h, IRremote.h



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: