Important: Please read the Qt Code of Conduct -

Get all urls in a text file

  • I have a text file with texts and urls, I want to get all the urls in that file, how can I do that using Qt?

  • Lifetime Qt Champion

    is it just a list of urls or is the url mixed with other type of text?
    Are you asking how you can parse them or how you would read the text file?
    Can you show some lines from the file?
    You can read all url lines by line this way

    QFile inputFile(fileName);
    if (
       QTextStream in(&inputFile);
       while (!in.atEnd())
          QString line = in.readLine();

  • It's a mixed text with urls. I think that the way you pointed out might have performance problem, am I wrong?

  • Lifetime Qt Champion

    well it reads one line at a time if that is what you mean.
    but it all depends how your text file is structured.
    if text are not neatly on lines (\n), reading it as lines is pointless.

  • Lifetime Qt Champion


    You can also load the content of your file completely and then run a search through it using QRegularExpression

  • @mrjj Actually the application doesn't need to know if it has lines or not, I just need to get all the links.

    I think that I will use regex:

    @SGaist I saw your answer before posting, but yes, I think that in this case it's better to use regex.

  • Lifetime Qt Champion

    Ok, so its like a dump.
    That is one nice RegularExpression ;)

  • @mrjj I just realized that this one isn't working with Qt. I'm getting a warning:

    QRegularExpressionPrivate::doMatch(): called on an invalid QRegularExpression object

    I will try to find other like this or make this one to work. - If you have one, I will accept too. haha.

  • Lifetime Qt Champion

    The actual expression should still work with the QRegularExpression Class ?
    seems just to add strings using + to make it more readable.
    "(?:(?:https?|ftp)://)" + "(?:\S+(?::\S*)?@)?" ...
    so you can easy convert to Qt , i think.

  • @mrjj That is how I'm doing it:

    QRegularExpression re(
      // protocol identifier
      // user:pass authentication
      // IP address exclusion
      // private & local networks
      // IP address dotted notation octets
      // excludes loopback network
      // excludes reserved space >=
      // excludes network & broacast addresses
      // (first & last IP address of each class)
      // host name
      // domain name
      // TLD identifier
      // TLD may end with dot
      // port number
      // resource path
    re.setPatternOptions(QRegularExpression::MultilineOption |
                       QRegularExpression::DotMatchesEverythingOption |
    auto match = re.match(text);
    if ( match.hasMatch()) {
      qDebug() << match.captured(0);
    } else {
      qDebug() << "Nothing found";

Log in to reply