1

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) {
    // ...
  }
vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80
  • Maybe `rex("([^_]*)_(\\d+\\.\\d+)_(\\d+\\.\\d+)")` will work as you need? Or even `rex("^([^_]*)_(\\d+\\.\\d+)_(\\d+\\.\\d+)")` if you need to match from the start of the string. – Wiktor Stribiżew Jan 26 '17 at 13:46

3 Answers3

2

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).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

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

Rene M.
  • 2,660
  • 15
  • 24
0

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);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125