带有可选扩展名的c++ 11正则表达式捕获文件名
C++11 regex capture file name with optional extension
我使用的是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)
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- C++11 (MSVS2012) 正则表达式在多行 std::string 中查找文件名
- 运行正则表达式时未选中的异常 - 从文件路径获取不带扩展名的文件名
- 在C++中使用正则表达式匹配文件名
- VS10 中文件名的正则表达式格式有什么问题<regex>?
- 带有可选扩展名的c++ 11正则表达式捕获文件名