What should QString::contains(QRegExp) return? May I use position meta-characters within the RegExp?

StackOverflow https://stackoverflow.com/questions/8541659

  •  19-03-2021
  •  | 
  •  

Question

I'm trying to detect if my input is a URL or a plain file path. I'm simply checking for http:// or www within the string, and that's enough for me.

So, I'm trying QString::contains(QRegExp) and I'm finding that it doesn't return what I expect it to. I've made a snippet to prove that it's bogus:

#include <QtCore>
#include <iostream>

int main(int argc, char *argv[]){
        std::cout << "true: " << true << std::endl;
        std::cout << "false: " << false << std::endl;
        if (argc > 1)
                std::cout << "input: " << (QString(argv[1]).contains(QRegExp("^[(http://)(www)]"))) << std::endl;
        return 0;
}

It should print 0 if the first parameter does not begin with www or http://, or 1 if it does. But, this are my results:

$ ./test
true: 1
false: 0
$ ./test foobar
true: 1
false: 0
input: 0
$ ./test www.google.com
true: 1
false: 0
input: 0x7fffa68f72df
$ ./test ww_foobar.com
true: 1
false: 0
input: 0x7fff177ba65f

Does anyone know what is going on?

Was it helpful?

Solution

Are you sure you are doing what you want?

^[(http://)(www)]

Means :

Match the start of the string, followed by one of (htp:/)w

What you probably wanted to write is :

std::cout << "input: " << (QString(argv[1]).contains(QRegExp("^(?:http://|www)"))) << std::endl;
        return 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top