PDA

View Full Version : Having a brain cramp on a regex



Spockmeat
13th July 2007, 21:14
I should probably just go home and get some sleep, but for the life of me I can't figure out why this regular expression isn't working.

Basically, what I want to do is take a list of strings and search through it looking for any string where any word in the string starts with the filter text. I thought I was pretty sure I have the regex correct, but no matter what I do I can't get it to work properly.


Here's my little filter function:


void MyDialog::filter(QString filterText)
{
// clear out the gui list
ui.stringList->clear(); // a combo box on my form holding a list of strings
// set up the regular expression
QRegExp regexp(QString("^.*\\b%1.*$").arg(filterText),Qt::CaseInsensitive,QRegExp::Wil dcard);
// strings is just a QStringList defined elsewhere
ui.stringList->addItems(strings.filter(regexp));
}


Now, if I make the QRegExp look like:

QRegExp regexp(QString("%1").arg(filterText),Qt::CaseInsensitive,QRegExp::Wil dcard);
It works just like I expect, filling the gui box with a list with lines from the full list where the filter text appears anywhere in any word from that string.

Admittedly, my knowledge on regular expressions is a bit rusty, but and maybe I'm just not forming the regular expression correctly, but I've been searching google for a while trying to remember this stuff and if I have something wrong I just can't see it.

I mean, even doing something simple like QString("^%1").arg(filterText) doesn't work. So I'm at a bit of a loss.

jacek
13th July 2007, 23:15
QRegExp regexp(QString("%1").arg(filterText),Qt::CaseInsensitive,QRegExp::Wil dcard);
The last parameter tells Qt to interpret your expression as a wildcard, not a regular expression. Either change it to QRegExp::RegExp or drop it.

Spockmeat
16th July 2007, 14:26
Wow, I feel dumb now :(

Thanks for that tip, works fine now.