我对以下正则表达式有问题:
prefix:\w+,\w+,\s*-?[0-9]{1,4}\s*,\s*-?[0-9]{1,4}\s*,\s*-?[0-9]{1,4}\s*,(?:\w+)
匹配字符串如下:
prefix:string,string,-100,100,0,string
我无法在我的 C 代码中匹配该字符串。至少我在一些网上获得了成功的匹配tool https://regex101.com/r/4yVSOH/2我在哪里生成了这个正则表达式。另外,正则表达式中存在有关“\”字符的编译警告,因此我按照中的说明替换了它c 编译器警告未知转义序列使用正则表达式用于 c 程序 https://stackoverflow.com/questions/18477153/c-compiler-warning-unknown-escape-sequence-using-regex-for-c-program。编译警告修复后的正则表达式:
prefix:\\w+,\\w+,\\s*-?[0-9]{1,4}\\s*,\\s*-?[0-9]{1,4}\\s*,\\s*-?[0-9]{1,4}\\s*,(?:\\w+)
这是测试代码:
#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, 0);
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;
}
我使用gcc版本6.2.0 20161005(Ubuntu 6.2.0-5ubuntu12)