使用regex检测带有特定前缀的DLL文件名

Detect a DLL file-name with a particular prefix using regex

本文关键字:前缀 DLL 文件名 regex 检测 使用      更新时间:2023-10-16

我正试图使用正则表达式模式来检测dll文件名是否:

  • module_
  • 开头
  • .dll
  • 结尾
  • 中间的字符均为非特殊字母数字字符
下面是我使用的代码:
bool IsModule(std::string const& name)
{
    static std::regex const regex("^module_[:alnum:]+\.dll");
    return std::regex_match(name, regex);
}

使用在线正则表达式调试器,我无法找出问题。当我使用module_custom.dll作为输入文件名进行测试时,它不认为它是匹配的。

[:alnum:]字符类似乎不支持c++ 11正则表达式引擎。根据这个页面,它相当于[a-zA-Z0-9],所以你可以这样做:

bool IsModule(std::string const& name)
{
    static std::regex const regex("^module_[a-zA-Z0-9]+\.dll$");
    return std::regex_match(name, regex);
}

请注意,我在末尾添加了$锚,正如Mike在上面的评论中提到的。如果省略它,它将认为module_custom.dllfoo是有效匹配。

[:alnum:]字符类是POSIX正则表达式风格的特性。我不熟悉c++中的正则表达式,但似乎默认引擎与EMACScript兼容,而不是POSIX。然而,根据这个页面,它看起来可能是可以切换到使用POSIX兼容的引擎?如果使用POSIX正则表达式语法对您很重要,也许有更有知识的人可以提供更多相关信息。

试试这个

bool IsModule(std::string const& name)
{
    static std::regex const regex("^module_\w+\.dll");
    return std::regex_match(name, regex);
}

不确定:alphanum:是否适用于c++ 11.