我試圖用regex.h匹配一個字符串「123,1234」。以下模式做的工作:正則表達式C
"^[0-9]\{1,\},[0-9]\{1,\}$"
如果我把它作爲命令行參數它工作正常。但是當我在C代碼中使用它時不起作用。可能是因爲將反斜線標識爲轉義字符。
示例代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
int main (int argc, char * argv[]){
regex_t regex;
int reti;
char msgbuf[100];
char * string, * pattern;
string = "123,1234";
pattern = "^[0-9]\{1,\},[0-9]\{1,\}$";
if(regcomp(®ex, pattern, 0))
{
fprintf(stderr, "Could not compile regex\n");
exit(107);
}
if(!(reti = regexec(®ex, string, 0, NULL, 0)))
{
printf("MATCH\n");
}
else if(reti == REG_NOMATCH)
{
printf("NO MATCH\n");
}
else
{
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(107);
}
regfree(®ex);
return 0;
}
我怎樣才能解決這個問題?
很難通過一個樣本來判斷,但模式看起來太複雜了,不是嗎? '^ \ d +,\ d + $' – Regexident 2011-06-14 16:21:22
@Regexident'+'既不能在grep中使用也不能使用regex.h – drox 2011-06-14 16:27:05
@Regexident我從這裏找到它[link](http://www.robelle.com/smugbook/regexpr。 HTML)它在grep中工作,以及如果我們將它作爲命令行參數傳遞給程序。 – drox 2011-06-14 16:33:08