在你的問題的模式是消費在state
的第一個字母與[^#]
,這在離開比賽無法繼續,因爲它試圖匹配tate
與模式\(state\)
。
你通過了國旗REG_EXTENDED
這意味着你不會逃避捕獲圓括號,但確實會轉義字面括號。
使用正則表達式,說你做要匹配:
^[ \\t]*(state)[ \\t]*:.*$
在
#include <stdio.h>
#include <regex.h>
int main(int argc, char **argv)
{
struct {
const char *input;
int expect;
} tests[] = {
/* should match */
{ "state : q0", 1 },
{ "state: q0", 1 },
{ "state:q0s", 1 },
/* should not match */
{ "#state :q0", 0 },
{ "state q0", 0 },
{ "# state :q0", 0 },
};
int i;
regex_t start_state;
const char *pattern = "^[ \\t]*(state)[ \\t]*:.*$";
if (regcomp(&start_state, pattern, REG_EXTENDED)) {
fprintf(stderr, "%s: bad pattern: '%s'\n", argv[0], pattern);
return 1;
}
for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
int status = regexec(&start_state, tests[i].input, 0, NULL, 0);
printf("%s: %s (%s)\n", tests[i].input,
status == 0 ? "match" : "no match",
!status == !!tests[i].expect
? "PASS" : "FAIL");
}
regfree(&start_state);
return 0;
}
輸出:
state : q0: match (PASS)
state: q0: match (PASS)
state:q0s: match (PASS)
#state :q0: no match (PASS)
state q0: no match (PASS)
# state :q0: no match (PASS)
可以請你發佈一些具體的例子? – 2010-02-04 17:37:37