Qt技巧:正则表达式提取字符串中的键值对数据

版权声明:欢迎转载,注明出处:来自CSDN博客作者弓人水。原文地址: https://blog.csdn.net/zzs0829/article/details/89228276

        分析网络数据或者通信数据的时候,经常需要从一大串字符串中去获取个别键值对的数据,简单的方法就是一个一个字符遍历并且判断关键字符,逻辑往往非常复杂,现在分享一种通过正则表达式提取键值对数据的方法。

        例如:下面是一串WIFI的事件反馈字符串,现在需要获取其中的一些数据,具体代码如下:

#include <QCoreApplication>
#include <QStringList>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString text = "P2P-DEVICE-FOUND 02:b5:64:63:30:63 "
                   "p2p_dev_addr=02:b5:64:63:30:63 pri_dev_type=1-0050f204-1 "
                   "name='Wireless Client' config_methods=0x84 dev_capab=0x21 "
                   "group_capab=0x0";
    QStringList items = text.split(QRegExp(" (?=[^']*('[^']*'[^']*)*$)"));
    QString event = items[0];
    QString addr = items[1];
    QString pri_dev_type;
    QString name = "";
    int config_methods = 0;
    int dev_capab = 0;
    int group_capab = 0;
    for (int i = 0; i < items.size(); i++) {
        QString str = items.at(i);
        if (str.startsWith("name='"))
            name = str.section('\'', 1, -2);
        else if (str.startsWith("pri_dev_type="))
            pri_dev_type = str.section('=', 1);
        else if (str.startsWith("config_methods="))
            config_methods = str.section('=', 1).toInt(0, 0);
        else if (str.startsWith("dev_capab="))
            dev_capab = str.section('=', 1).toInt(0, 0);
        else if (str.startsWith("group_capab="))
            group_capab = str.section('=', 1).toInt(0, 0);
    }

    qDebug() << event;
    qDebug() << addr;
    qDebug() << pri_dev_type;
    qDebug() << name;
    qDebug("0x%x", config_methods) ;
    qDebug("0x%x", dev_capab) ;
    qDebug("0x%x", group_capab) ;

    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/zzs0829/article/details/89228276