【发布时间】:2016-10-23 17:27:55
【问题描述】:
我不明白为什么包含\d 字符类的正则表达式模式不起作用但[0-9] 起作用。字符类,例如\s(空白字符)和\w(单词字符),可以工作。我的编译器是 gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3。我正在使用 C 正则表达式库。
为什么\d 不起作用?
文本字符串:
const char *text = "148 apples 5 oranges";
对于上面的文本字符串,这个正则表达式不匹配:
const char *rstr = "^\\d+\\s+\\w+\\s+\\d+\\s+\\w+$";
当使用 [0-9] 而不是 \d: 时,此正则表达式匹配:
const char *rstr = "^[0-9]+\\s+\\w+\\s+[0-9]+\\s+\\w+$";
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#define N_MATCHES 30
// output from gcc --version: gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
// compile command used: gcc -o tstc_regex tstc_regex.c
const char *text = "148 apples 5 oranges";
const char *rstr = "^[0-9]+\\s+\\w+\\s+[0-9]+\\s+\\w+$"; // finds match
//const char *rstr = "^\\d+\\s+\\w+\\s+\\d+\\s+\\w+$"; // does not find match
int main(int argc, char**argv)
{
regex_t rgx;
regmatch_t matches[N_MATCHES];
int status;
status = regcomp(&rgx, rstr, REG_EXTENDED | REG_NEWLINE);
if (status != 0) {
fprintf(stdout, "regcomp error: %d\n", status);
return 1;
}
status = regexec(&rgx, text, N_MATCHES, matches, 0);
if (status == REG_NOMATCH) {
fprintf(stdout, "regexec result: REG_NOMATCH (%d)\n", status);
}
else if (status != 0) {
fprintf(stdout, "regexec error: %d\n", status);
return 1;
}
else {
fprintf(stdout, "regexec match found: %d\n", status);
}
return 0;
}
【问题讨论】:
-
我猜
\d会匹配d? -
我没有找到任何说 libc 不支持Shorthand Character Classes。
-
正则表达式的优点之一是有很多风格可供选择。