Search code examples
regexqregexp

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) {
    // ...
  }

Solution

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