Qt Regular Expression selects from first of first match to end of last match

689 Views Asked by At

I'm using QRegExp for geting some directories in a file. All of them start with "R:/ and finish with .c". So I used "R:/(.*).c" regex statement.

But it has 1 match for below text :

Text :

mov       f1, dsa
lis       r9, sdefwf "R:/frori.c"
addi      r3, r9, cwrfg "R:/DWors.c"
li        r4, 0*uy
dfr       R:/DWors.c
dew       d2, fref

Matched Text :

frori.c"
addi      r3, r9, cwrfg "R:/DWors.c"
li        r4, 0*uy
dfr       R:/DWors

Match case starts with the first R: and ends with the last .c of text, but I need detect 3 matches in this example.

I searched for the answer, and find ? for .*; something like "R:/(. *?).c" statement that has to result for my example.(no match)

I want a regex statement that find 3 matches in my text.

------------------------------------------------------------------------------------------------------------

Update: Maybe I'm wrong in using QRegExp functions.

here is my code :

QString fileName = QFileDialog::getOpenFileName(this, tr("Open Text file"), "", tr("All Files (*.*)"));

QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
   return;

QString str;
QString dir;

while (!file.atEnd()) {
   str = file.readAll();
}

QRegExp rx("R:(.*)\.c");

int pos = 0;

while ((pos = rx.indexIn(str, pos)) != -1) {
       dir.append(rx.cap(1));
       dir.append('\n');
       pos += rx.matchedLength();
   }

qDebug() << dir;
3

There are 3 best solutions below

0
On BEST ANSWER

The * operator is usually greedy in Qt Regexp. You can change this by calling setMinimal(true)

Greedy regexps try to consume as much as possible, and therefore behave exactly as you are experiencing. Minimal Regexps try to match as little as possible. This should solve your problem, as the matching will stop at the c character

0
On

Use a negated character class.

"R:/[^.]*[.]c"
0
On

You can use this regex: R:.*\.c

Demo