V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
haozhang
V2EX  ›  C

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

  •  1
     
  •   haozhang · 2019-06-07 22:05:05 +08:00 · 2534 次点击
    这是一个创建于 1777 天前的主题,其中的信息可能已经有所发展或是发生改变。

    求助,关于 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);
    }
    
    5 条回复    2019-06-08 10:44:37 +08:00
    vibbow
        1
    vibbow  
       2019-06-08 02:39:34 +08:00   ❤️ 2
    首先,每家正则式引擎的用法都是有些差异的,并不是想象中的那种通用的。

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

    https://www.regexbuddy.com/
    May725
        2
    May725  
       2019-06-08 03:45:48 +08:00 via iPhone   ❤️ 1
    正则语法或功能的支持可能并不是完全相同。
    调试时,建议先缩短表达式,逐步确认,最后找出不能匹配的原因。
    haozhang
        3
    haozhang  
    OP
       2019-06-08 07:55:47 +08:00 via Android
    @May725 谢谢
    haozhang
        4
    haozhang  
    OP
       2019-06-08 07:56:01 +08:00 via Android
    @vibbow 我去试试,谢谢
    SmallZheng
        5
    SmallZheng  
       2019-06-08 10:44:37 +08:00
    \d 换成 [0-9] 试试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2824 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 11:29 · PVG 19:29 · LAX 04:29 · JFK 07:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.