V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
haozhang
V2EX  ›  C

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

  •  1
     
  •   haozhang · Jun 7, 2019 · 3157 views
    This topic created in 2521 days ago, the information mentioned may be changed or developed.

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

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

    https://www.regexbuddy.com/
    May725
        2
    May725  
       Jun 8, 2019 via iPhone   ❤️ 1
    正则语法或功能的支持可能并不是完全相同。
    调试时,建议先缩短表达式,逐步确认,最后找出不能匹配的原因。
    haozhang
        3
    haozhang  
    OP
       Jun 8, 2019 via Android
    @May725 谢谢
    haozhang
        4
    haozhang  
    OP
       Jun 8, 2019 via Android
    @vibbow 我去试试,谢谢
    SmallZheng
        5
    SmallZheng  
       Jun 8, 2019
    \d 换成 [0-9] 试试
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   762 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 21:14 · PVG 05:14 · LAX 14:14 · JFK 17:14
    ♥ Do have faith in what you're doing.