
因为自己写的正则死活匹配不了,就搜了半天 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(®ex, REGEX, REG_EXTENDED); if (rc != 0) { fprintf(stderr, "Could not compile regex\n"); exit(1); } rc = regexec(®ex, 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 编译结果都能匹配。
1 lindt99cocoa 2022 年 3 月 14 日 可以复现 LZ 的问题 同时用 C++ 11 的 regex 试了一下,是可以 match 的 |
2 ynyounuo 2022 年 3 月 14 日 貌似是 \\w+ 的问题,换成 \\w* 就没问题了,而且 \\w{1,..} 这种也不行,必须要 \\w{0,..} 才能 match |
3 ynyounuo 2022 年 3 月 14 日 貌似是因为 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 |
4 villivateur 2022 年 3 月 14 日 你可以找一个 regex.c 自己来编译,不要用 mac 自带的链接库 |
5 dianqk 2022 年 3 月 14 日 改成? ``` rc = regcomp(®ex, REGEX, REG_EXTENDED | REG_ENHANCED); ``` |