vlad_tepesch
vlad_tepesch

Reputation: 6883

why does this regex does not match?

Why does the following code does not match? the expression is not that difficult and online regex tester also state that it should work. Am i doing something wrong with the escapes?

  QRegExp rex("(.*?)(\\d+\\.\\d+)_(\\d+\\.\\d+).*?");
  QString fileName("tile_10.0000_47.3100_0.1_.dat");

  if (rex.indexIn(fileName)>=0) {
    // ...
  }

Upvotes: 1

Views: 120

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

You can also change quantifiers behaviour with QRegExp.setMinimal() to make them non-greedy by default and with a little change to your pattern:

QRegExp rex("(.*)(\\d+\\.\\d+)_(\\d+\\.\\d+)(\\D.*|$)");
rex.setMinimal(true);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

QRegExp does not support lazy quantifiers, so *? does not work here. Also, the .*? at the end of the pattern does not match any text, it can safely be removed.

I suggest replacing the first .*? with ([^_]*)_ pattern (0+ chars other than _ and a _ right after them) to get to the first digits.digits text:

rex("([^_]*)_(\\d+\\.\\d+)_(\\d+\\.\\d+)")

Or, if you need to match the data from the start of the string, prepend the pattern with ^ (start of string).

Upvotes: 2

Rene M.
Rene M.

Reputation: 2690

One possile change could be:

(.*?)(\d+\.\d+)_(\d+\.\d+)_(\d+\.\d+)_\..*

Which is very strict to your example.

And here one which accepts any sequence of numbers followed by underscores till file extension.

(.*?)((\d+\.\d+)_+)\..*

Hope that helps

Upvotes: 0

Related Questions