Qt程序设计之正则表达式的简单示例

正则表达式(Regular Expression)描述了一种字符串匹配的模式(Pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

#include <QRegularExpression>

int main(void)
{
    QString data = "<Person><Item><ID>100001</ID><NAME>CHN</NMAE><AGE>5500</AGE></Item>"
                   "<Item><ID>100002</ID><NAME>USA</NMAE><AGE>300</AGE></Item></Person>";
    QRegularExpression re("<Item><ID>(.*?)</ID><NAME>(.*?)</NMAE><AGE>(.*?)</AGE></Item>");

    QRegularExpressionMatchIterator it = re.globalMatch(data);
    while (it.hasNext())
    {
        QRegularExpressionMatch match = it.next();
        qDebug() << match.captured(1).toUtf8().data()
                 << match.captured(2).toUtf8().data()
                 << match.captured(3).toUtf8().data();
    }

    return 0;
}

Leave a Reply

Your email address will not be published.