带有可选扩展名的c++ 11正则表达式捕获文件名

C++11 regex capture file name with optional extension

本文关键字:正则表达式 文件名 c++ 扩展名      更新时间:2023-10-16

我使用的是g++ 4.9.0,所以它确实支持正则表达式:)我试图用可选扩展名提取文件名:

#include <regex>
smatch match_result;
regex pattern("/home/user/(.+)(\.png)?$");
if (!regex_search("/home/user/image.png", match_result, pattern) {
    throw runtime_error("Path does not match the pattern.");
}
cout << "File name: " << match_result[1] << 'n';

运行这个代码片段,当我期待image时,输出image.png。显然,+量词是贪婪的,忽略了下面的模式(\.png)?$。有什么办法可以避免这种情况吗?或者我应该手动修剪扩展?

使用(.+?)。问号使模式不贪婪。我猜你还需要^

完整模式:"^/home/user/(.+?)(\.png)?$" .

您可能还想使用忽略大小写匹配

从索引1中获取匹配的组

这里是DEMO

程序中使用的字符串字面值:

c#

@"/(w+).png$"

您的代码示例不使用regex pattern("/home/user/(.+)(\.png)?$")。它使用您在调用regex_search():

时创建的新正则表达式。
regex_search("/home/user/image.png", match_result, regex("/home/user/(.+)"))

您实际使用的正则表达式不检查.png扩展。

试试这个:

regex_search("/home/user/image.png", match_result, pattern)