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

2022-03-13 22:12:32 +08:00
 stimw

因为自己写的正则死活匹配不了,就搜了半天 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 编译结果都能匹配。

1914 次点击
所在节点    Apple
5 条回复
lindt99cocoa
2022-03-14 00:21:58 +08:00
可以复现 LZ 的问题
同时用 C++ 11 的 regex 试了一下,是可以 match 的
ynyounuo
2022-03-14 01:28:39 +08:00
貌似是 \\w+ 的问题,换成 \\w* 就没问题了,而且 \\w{1,..} 这种也不行,必须要 \\w{0,..} 才能 match
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
2022-03-14 08:55:04 +08:00
你可以找一个 regex.c 自己来编译,不要用 mac 自带的链接库
DianQK
2022-03-14 10:41:35 +08:00
改成?
```
rc = regcomp(&regex, REGEX, REG_EXTENDED | REG_ENHANCED);
```

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

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

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

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

© 2021 V2EX