求助,关于 C 的正则表达式, regex 的使用。

2019-06-07 22:05:05 +08:00
 haozhang

求助,关于 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(&reg, pattern, REG_ENHANCED | REG_EXTENDED); 
if (result != 0)
{
    perror("Could not compile regex");
    exit(EXIT_FAILURE);
}
int status = regexec(&reg, &line[i], 1, match, 0);
if (status == REG_NOMATCH)
{
     // no match
     regfree(&reg);
}
else if (status == 0)
{
     // matched
     // do something here
}
else
{
    perror("Regex in exceptional situations, match identifier failed");
    exit(EXIT_FAILURE);
}
2543 次点击
所在节点    C
5 条回复
vibbow
2019-06-08 02:39:34 +08:00
首先,每家正则式引擎的用法都是有些差异的,并不是想象中的那种通用的。

其次,Regex Buddy 你值得拥有,可以帮你在各种正则式引擎之间转换规则。

https://www.regexbuddy.com/
May725
2019-06-08 03:45:48 +08:00
正则语法或功能的支持可能并不是完全相同。
调试时,建议先缩短表达式,逐步确认,最后找出不能匹配的原因。
haozhang
2019-06-08 07:55:47 +08:00
@May725 谢谢
haozhang
2019-06-08 07:56:01 +08:00
@vibbow 我去试试,谢谢
SmallZheng
2019-06-08 10:44:37 +08:00
\d 换成 [0-9] 试试

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/571858

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX