QRegExp:单个量词不可能是非贪婪的,那么有什么好的选择呢?



我正在尝试编写将结尾_my_ending附加到文件名的代码,并且不会更改文件扩展名。

我需要获得的示例:

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

我在PCRE方面有一些经验,使用它是一项微不足道的任务。由于缺乏Qt的经验,最初我编写了以下代码:

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

这段代码不起作用(根本没有匹配),然后我在文档中发现

非贪婪匹配不能应用于单个量词,但可以应用于模式中的所有量词

如您所见,在我的正则表达式中,我试图通过在第一个量词+之后添加?来减少贪婪。这在 QRegExp 中不受支持。

这对我来说真的很令人失望,因此,我必须编写以下丑陋但有效的代码:

//-- 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;
}

但是有没有更好的解决方案?我喜欢Qt,但我在其中看到的一些东西似乎令人沮丧。

使用 QFileInfo 怎么样?这比你的"丑陋"代码短:

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

最新更新