2012-09-11 23 views
1

下面找到美元符號是我的代碼中,我想找到字符串是否含有$符號或沒有,但它顯示錯誤:error: unknown escape sequence '\$'如何使用regex.h

#include <sys/types.h> 
#include <regex.h> 
#include <stdio.h> 

#define MAX_MATCHES 1 //The maximum number of matches allowed in a single string 

void match(regex_t *pexp, char *sz) { 
     regmatch_t matches[MAX_MATCHES]; //A list of the matches in the string (a list of 1) 
     //Compare the string to the expression 
     //regexec() returns 0 on match, otherwise REG_NOMATCH 
     if (regexec(pexp, sz, MAX_MATCHES, matches, 0) == 0) { 
       printf(" matches characters "); 
     } else { 
       printf(" does not match\n"); 
     } 
} 

int main() { 
     int rv; 
     regex_t exp; //Our compiled expression 
     //1. Compile our expression. 
     //Our regex is "-?[0-9]+(\\.[0-9]+)?". I will explain this later. 
     //REG_EXTENDED is so that we can use Extended regular expressions 
     rv = regcomp(&exp, "\$", REG_EXTENDED); 
     if (rv != 0) { 
       printf("regcomp failed with %d\n", rv); 
     } 
     //2. Now run some tests on it 
     match(&exp, "Price of iphone is $800 "); 

     //3. Free it 
     regfree(&exp); 
     return 0; 
} 

回答

4

您需要轉義反斜線:當你想創建一個字符串,其中包括一個

rv = regcomp(&exp, "\\$", REG_EXTENDED); 
3

逃離字符串字面的反斜槓又道:「\\$"

1

反斜槓,像這樣的正則表達式,你需要逃避與另一個反斜槓反斜槓:

regcomp(&exp, "\\$", REG_EXTENDED); 
3

我沒有做過ç正則表達式的一段時間,但是從內存中,你必須加倍他們逃脫反斜槓,因爲第一一個被視爲C逃逸,第二個被傳遞給正則表達式引擎作爲$的逃逸。即\\$

由於是又一個例子,如果你要檢查在C正則表達式一個反斜槓,你需要使用\\\\