Search code examples
c++regexqtqregexp

Extracting the filename off a URL with QRegExp


I have an issue where I have a RegEx, [^/\&\?]+.\w{3,4}(?=([\?&].*$|$)), but I cannot get it to work with the function at [ 1 ] below.

[ 1 ] - http://doc.qt.io/qt-5/qregexp.html

This is the code I've tried:

QRegExp rx("[^/\\\\&\\?]+\\.\\w{3,4}(?=([\\?&].*$|$))", Qt::CaseInsensitive, QRegExp::RegExp);
std::ostringstream list;
int pos = 0;
while ((pos = rx.indexIn(url, pos)) != -1) {
    list << rx.cap(1).toStdString();
    pos += rx.matchedLength();
}

return list;

It's supposed to extract the filename off a URL, but just returns nothing instead. I'm not sure what's going wrong. Can someone please offer assistance? Thank you in advance.


Solution

  • Qt has QUrl class for parsing URL etc. And there is QUrl::fileName method:

    QUrl url("http://qt-project.org/support/file.html");
    // url.adjusted(RemoveFilename) == "http://qt-project.org/support/"
    // url.fileName() == "file.html"