求助,关于 C 的正则表达式:
用 POSIX 的 regex 写了一个正则表达式:^[^\()[]{}",';#\|\s^\d{1,}$]+, 然后在程序里用 const char *pattern = "^[^\\\\\\(\\)\\[\\]\\{\\}\",';#\|\s^\d{1,}$]+",
匹配“ define a '(11 2.2 233 "abcd" "123abc"))”字符串中的 define,但是匹配不到,而我在一些正则表达式测试网站,用同样一套 pattern 和 string,是可以匹配到 define 这个单词的。
代码片段如下:
const char *pattern = "^[^\\\\\\(\\)\\[\\]\\{\\}\",'`;#\\|\\s^\\d{1,}$]+";
regex_t reg;
regmatch_t match[1];
int result = regcomp(®, pattern, REG_ENHANCED | REG_EXTENDED);
if (result != 0)
{
perror("Could not compile regex");
exit(EXIT_FAILURE);
}
int status = regexec(®, &line[i], 1, match, 0);
if (status == REG_NOMATCH)
{
// no match
regfree(®);
}
else if (status == 0)
{
// matched
// do something here
}
else
{
perror("Regex in exceptional situations, match identifier failed");
exit(EXIT_FAILURE);
}