2

I'm trying to write code that appends ending _my_ending to the filename, and does not change file extension.

Examples of what I need to get:

"test.bmp"            -> "test_my_ending.bmp"
"test.foo.bar.bmp"    -> "test.foo.bar_my_ending.bmp"
"test"                -> "test_my_ending"

I have some experience in PCRE, and that's trivial task using it. Because of the lack of experience in Qt, initially I wrote the following code:

QString new_string = old_string.replace(
      QRegExp("^(.+?)(\\.[^.]+)?$"),
      "\\1_my_ending\\2"
      );

This code does not work (no match at all), and then I found in the docs that

Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern

As you see, in my regexp I tried to reduce greediness of the first quantifier + by adding ? after it. This isn't supported in QRegExp.

This is really disappointing for me, and so, I have to write the following ugly but working code:

//-- write regexp that matches only filenames with extension
QRegExp r = QRegExp("^(.+)(\\.[^.]+)$");
r.setMinimal(true);

QString new_string;

if (old_string.contains(r)){
   //-- filename contains extension, so, insert ending just before it
   new_string = old_string.replace(r, "\\1_my_ending\\2");
} else {
   //-- filename does not contain extension, so, just append ending
   new_string = old_string + time_add;
}

But is there some better solution? I like Qt, but some things that I see in it seem to be discouraging.

2
  • I don't know if this helps, but I know that QRegExp has some different modes than the default mode, namely QRegExp::RegExp2. You can switch the mode by calling r.setPatternSyntax(...). The doc says, that RegExp2 introduces "greedy quantifiers".
    – leemes
    Dec 7, 2012 at 10:33
  • 1
    Unfortunately this doesn't help with that task. The only difference of RegExp2 from RegExp is that RegExp's quantifiers that apply to capturing parentheses are more "greedy" than other quantifiers, which is confusing. RegExp2 fixes that. Thanks for the information, though. Dec 7, 2012 at 11:03

1 Answer 1

1

How about using QFileInfo? This is shorter than your 'ugly' code:

QFileInfo fi(old_string);
QString new_string = fi.completeBaseName() + "_my_ending" 
    + (fi.suffix().isEmpty() ? "" : ".") + fi.suffix();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.