【发布时间】:2016-03-15 07:41:31
【问题描述】:
以下面的 API regex_match 为例,如果我用 regex_match(any_string_here,"") 调用它,你可以看到我在这里传递了一个空的正则表达式,那么它总是返回 0,表示匹配成功。那么,POSIX BRE/ERE 中的空正则表达式是什么意思?
空正则表达式意味着我将 "" 传递给 glibc regcomp 函数。请参阅以下示例。
int regex_match( const char* haystack, const char* needle )
{
regex_t needle_pattern;
int regex_flag = REG_NOSUB | REG_EXTENDED;
int rc = regcomp(&needle_pattern,needle, regex_flag);
if (rc != 0){
char error_msg[256];
size_t error_len = 0;
error_len = regerror(rc,&needle_pattern,error_msg,sizeof(error_msg));
error_len = error_len < sizeof(error_msg) ? error_len : sizeof(error_msg) - 1;
error_msg[error_len] = '\0';
cout<<"compile error: "<<error_msg<<endl;
regfree(&needle_pattern);
return regcomp_error_base + rc;
}
rc = regexec(&needle_pattern, haystack, 0, NULL, 0);
if ( (rc != 0) && (rc != REG_NOMATCH)){
char error_msg[256];
size_t error_len = 0;
error_len = regerror(rc,&needle_pattern,error_msg,sizeof(error_msg));
error_len = error_len < sizeof(error_msg) ? error_len : sizeof(error_msg) - 1;
error_msg[error_len] = '\0';
cout<<"exec error: "<<error_msg<<endl;
}
regfree(&needle_pattern);
//regexec returns 0 if the regular expression matches
return rc;
}
【问题讨论】:
-
不确定
empty表达式的含义。我的意思是,是这个//还是这个/^$/或/.*?/。我猜如果它什么都不匹配,它就不能被假定为一个空表达式,并且可能也没有说任何关于主题字符串的内容。最好的办法是在使用主题和正则表达式字符串之前测试它们的长度。 -
POSIX 正则表达式语法不允许空模式。行为未定义。您可能会遇到一个无限循环(MacOS C++ 就是这种情况)。
-
我猜他们的关键字是它匹配的东西,虽然它从字面上什么都不匹配。
-
@sln 空正则表达式意味着我将 "" 传递给 glibc regcomp 函数。例如regcomp(&needle_pattern,"", regex_flag);
-
@stribizhev glibc 函数 regcomp 允许空的正则表达式,请看我的例子。
标签: regex posix glibc posix-ere