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

为什么这段 C 的正则判断,在 m1 的 mac 上使用 apple clang 编译运行结果不匹配?

  •  
  •   stimw · 2022-03-13 22:12:32 +08:00 · 1891 次点击
    这是一个创建于 773 天前的主题,其中的信息可能已经有所发展或是发生改变。

    因为自己写的正则死活匹配不了,就搜了半天 c 的正则怎么写,发现别人的也不匹配。

    下面举例的代码是网上别人的: https://ideone.com/TH5t3U

    #include <stdio.h>
    #include <regex.h>        
    #include <stdlib.h>
     
    #define REGEX "prefix:\\w+,\\w+,\\s*-?[0-9]{1,4}\\s*,\\s*-?[0-9]{1,4}\\s*,\\s*-?[0-9]{1,4}\\s*,\\w*"
     
    const char *input = "prefix:string,string,-100,100,0,string";
    int main(){
     
        int rc;
     
        regex_t regex;
     
        rc = regcomp(&regex, REGEX, REG_EXTENDED);
        if (rc != 0) {
            fprintf(stderr, "Could not compile regex\n");
            exit(1);
        }
     
        rc = regexec(&regex, input, 0, NULL, 0);
        if (rc == 0) {
            printf("Match!\n");
            return 0;
        }
        else if (rc == REG_NOMATCH) {
            printf("No match\n");
            return -1;
        }
        else {
            perror("Error\n");
            exit(1);
        }
     
        return 0;
    }
    

    还以为自己傻了,折腾了半天,到后来发现这个正则我在 arm linux 上,无论是 gcc 还是 clang 编译结果都能匹配。

    5 条回复    2022-03-14 10:41:35 +08:00
    lindt99cocoa
        1
    lindt99cocoa  
       2022-03-14 00:21:58 +08:00
    可以复现 LZ 的问题
    同时用 C++ 11 的 regex 试了一下,是可以 match 的
    ynyounuo
        2
    ynyounuo  
       2022-03-14 01:28:39 +08:00
    貌似是 \\w+ 的问题,换成 \\w* 就没问题了,而且 \\w{1,..} 这种也不行,必须要 \\w{0,..} 才能 match
    ynyounuo
        3
    ynyounuo  
       2022-03-14 03:11:48 +08:00
    貌似是因为 macOS 本身的 regex lib 即使有 REG_EXTENDED 也不支持 \w

    简单测试了一下
    > ls
    > '\w.txt' a.txt w.txt
    > find -E . -type f -regex './\\w.txt'
    > ./\w.txt
    > find -E . -type f -regex './\w.txt'
    > ./w.txt
    > /usr/local/opt/findutils/libexec/gnubin/find -regextype posix-extended -regex './\w.txt'
    > ./w.txt
    > ./a.txt
    villivateur
        4
    villivateur  
       2022-03-14 08:55:04 +08:00
    你可以找一个 regex.c 自己来编译,不要用 mac 自带的链接库
    DianQK
        5
    DianQK  
       2022-03-14 10:41:35 +08:00
    改成?
    ```
    rc = regcomp(&regex, REGEX, REG_EXTENDED | REG_ENHANCED);
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1653 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 16:53 · PVG 00:53 · LAX 09:53 · JFK 12:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.