QT - 正则表达式

一、提取字符串

    QString str = "Hello 123321 world 12313 !";
    QRegExp rx(R"""([\d]+)""");
    int pos = 0;
    while((pos = rx.indexIn(str,pos)) != -1){
        QStringList list = rx.capturedTexts();
        pos += rx.matchedLength();
        qDebug() << list;
    }

结果为:

("123321")
("12313")

二、替换字符串

1、普通正则替换

    QString str = "Hello 123321=a world 12313=b !";
    QRegExp rx(R"""([\d]+)""");
    QString newStr = str.replace(rx,"number");
    qDebug() << newStr;

结果为:

"Hello number=a world number=b !"

2、占位符替换

    QString str = "Hello 123321=a world 12313=b !";
    QRegExp rx(R"""(([\d]+)=([\w]))""");
    QString newStr = str.replace(rx,R"""(\1\2=\2)""");
    qDebug() << newStr;

结果为:

"Hello 123321a=a world 12313b=b !"








猜你喜欢

转载自blog.csdn.net/wyansai/article/details/80586957