PDA

View Full Version : QRegExp Confusion



redneon
20th April 2009, 10:20
I'm helping a friend of mine port a small application he's written from C# .NET to C++ QT and we've come across a little snag with the regular expressions.

In C# .NET we have a piece of code which looks similar to this:



private bool ValidURL(string url)
{
RegEx validURLRegex = new Regex("^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/?.*)$");
if (validURLRegex.IsMatch(url))
return true;
return false;
}


I'm trying to convert this to use QRegExp (which I'm new to) and the code I come up with is this:



void SomeClass::ValidURL(QString url)
{
QRegExp validURLRegex("^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/?.*)$");
if (validURLRegex.exactMatch(url))
return true;
return false;
}


This doesn't seem to work, however. I've tried various things, such as calling setMinimal(true) (not sure whether .NET uses greedy matching or not) and I've also tried setting the pattern syntax to all the available options, to no avail.

Any ideas?

Lykurg
20th April 2009, 10:36
Hi, may you could use QUrl::isValid() and then I am not sure if every "." should have the meaning "any character. If you mean only a point use "\\."

EDIT: [-.]{1} should be [\\-\\.]{1} etc.

redneon
20th April 2009, 10:42
I did spot QUrl::IsValid() but that seemed to return true no matter what I gave it. Even simple strings such as "notavalidurl" would return true.

SnarlCat
21st April 2009, 11:33
Try coupling your QRegExp with a QRegExpValidator. Use the QRegExpValidator function validate(...) to check... Something along the lines of this should do the trick:



void SomeClass::ValidURL(QString url)
QRegExp validURLRegex("^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/?.*)$");
QRegExpValidator validator(validURLRegex);
int index = 0;
if (validator.validate(url, index) == QValidator::Acceptable)) {
return true;
} else {
return false;
}
}


As a bonus, you could use your QRegExp/QRegExpValidator with an input widget (think QLineEdit) so that only valid values can be entered.... (Not sure how this fits into the greater scheme, so maybe this isn't appropriate for you..)