PDA

View Full Version : Negative regexp



mero
30th January 2013, 16:21
Hello,

I have problem with negative regexp in QT,
I've want capture string after "//"
example: in "//aaa" - i want "aaa"
but I dont want capture when before "//" is http: or https:

I've tried this 4 regexp, but all are wrong ...

please help



#include <QCoreApplication>
#include <QRegExp>
#include <QDebug>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QRegExp rx1("(ftp:|http:|https:){0}//([a-zA-Z0-9_-]+)");
QRegExp rx2("[^(ftp:|http:|https:)]//([a-zA-Z0-9_-]+)");
QRegExp rx3("(?=(ftp:|http:|https:))//([a-zA-Z0-9_-]+)");
QRegExp rx4("(?!(ftp:|http:|https:))//([a-zA-Z0-9_-]+)");

QString strData;
strData = "//aaa";

// should be != -1
qDebug() << "1:" << rx1.indexIn(strData) << " " << (rx1.indexIn(strData) != -1 ? "OK" : "WRONG");
qDebug() << "2:" << rx2.indexIn(strData) << " " << (rx2.indexIn(strData) != -1 ? "OK" : "WRONG");
qDebug() << "3:" << rx3.indexIn(strData) << " " << (rx3.indexIn(strData) != -1 ? "OK" : "WRONG");
qDebug() << "4:" << rx4.indexIn(strData) << " " << (rx4.indexIn(strData) != -1 ? "OK" : "WRONG");

qDebug() << "";
strData = "http://aaa";

// should be == -1
qDebug() << "1:" << rx1.indexIn(strData) << " " << (rx1.indexIn(strData) == -1 ? "OK" : "WRONG");
qDebug() << "2:" << rx2.indexIn(strData) << " " << (rx2.indexIn(strData) == -1 ? "OK" : "WRONG");
qDebug() << "3:" << rx3.indexIn(strData) << " " << (rx3.indexIn(strData) == -1 ? "OK" : "WRONG");
qDebug() << "4:" << rx4.indexIn(strData) << " " << (rx4.indexIn(strData) == -1 ? "OK" : "WRONG");

// rx.cap ... etc

return a.exec();
}

maximebd
30th January 2013, 21:59
?! is the negative lookahead operator, it doesn't work for stuff before. What you can do is to have a non-capturing group to define a group that starts the line with ^https?://.*

I haven't tested it, but it should look like:


QRegExp rx("(?:^(?:ftp|http|https)://.*$)?//(\\w+)");

I am not sure of the usage of a non-capturing group within a non-capturing group. You might need to use (?:ftp://.*|http://.*|https://.*) instead.

- Maxime