Search code examples
c++regexqtqregularexpression

Extract strings inside double quotes with QRegularExpression


I have a string like below:

on prepareFrame
  go to frame 10
    goToNetPage "http://www.apple.com"
    goToNetPage "http://www.cnn.com"
    etc..
end 

I want to extract all the urls from this string by using QRegularExpression. I've already tried:

QRegularExpression regExp("goToNetPage \"\\w+\"");
QRegularExpressionMatchIterator i = regExp.globalMatch(handler);
while (i.hasNext()) {
    QRegularExpressionMatch match = i.next();
    QString handler = match.captured(0);
}

But this not working.


Solution

  • You may use

    QRegExp regExp("goToNetPage\\s*\"([^\"]+)");
    QStringList MyList;
    int pos = 0;
    
    while ((pos = regExp.indexIn(handler, pos)) != -1) {
        MyList << regExp.cap(1);
        pos += regExp.matchedLength();
    }
    

    The pattern is

    goToNetPage\s*"([^"]+)
    

    It matches goToNetPage, 0 or more whitespace chars, " and then captures into Group 1 any 1+ chars other than " - the required value is accessed using regExp.cap(1).