-2
我试图使用正则表达式来验证文件名。 试过这个字符串regcomp()失败,'成功'
"^(?!(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.[^.]*)?$)[^<>:\"/\\\|\\?*\x00-\x1F]*[^<>:\"/\\\|\?*\x00-\x1F\\ .]$"
在网上检查:https://www.freeformatter.com/regex-tester.html 作品如预期的 'video-'
- >完全处于源字符串相匹配!
但是,使用:
bool regexCompile(regex_t ®ex, const char *pattern)
{
int res = 0;
res = regcomp(®ex, pattern, REG_EXTENDED);
printf("res = %d\n",res);
if(res) // regex compiled unsuccessfully
{
int rc;
char buffer[100];
regerror(rc, ®ex, buffer, 100);
printf("regcomp() failed with '%s'\n", buffer);
return false;
}
return true;
}
bool isValidFileName(const char *fileName)
{
regex_t regex;
int res = 0;
// regex not complete
const char* pattern = "^(?!(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\\.[^.]*)?$)[^<>:\"/\\\\|?*\x00-\x1F]*[^<>:\"/\\\\|\\?*\x00-\x1F\\ .]$";
if(regexCompile(regex, pattern) != true)
{
return false;
}
res = regexec(®ex, fileName, 0, NULL, 0);
if(!res)
{
return true;
}
return false;
}
我得到的文件名 “video-”:
res = 13
regcomp() failed with 'Success'
0
任何额外的反斜杠需要在C-正则表达式版本添加? 谢谢。
告诉你的代码是不是C,它可能是C++(在这种情况下,你应该使用[C++标准的正则表达式的功能( http://en.cppreference.com/w/cpp/regex))。 –
什么是'regexCompile(regex_t&regex ...'?除了“不是C代码”? –
请注意POSIX [正则表达式](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html) ,即使是ERE变体,也不处理PCRE'(?...)'符号,因此,您需要[PCRE](https://pcre.org/)。因此,即使您解决了其他问题,正则表达式可能不符合你的期望 –