2013-10-12 33 views
1

嗨我想检查一个字符串是否包含带有GNU正则表达式的“abc”,我试过\b\w但它们都不起作用。如何检查一个字符串是否包含GNU正则表达式中的几个字符?

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

int main(int argc, char *argv[]){ 
     regex_t regex; 
     int reti; 
     char msgbuf[100]; 

/* Compile regular expression */ 
     //reti = regcomp(&regex, "\wabc\w", 0); 
     reti = regcomp(&regex, "\babc\b", 0); 
     if(reti){ fprintf(stderr, "Could not compile regex\n"); exit(1); } 

/* Execute regular expression */ 
     reti = regexec(&regex, "123abc123", 0, NULL, 0); 
     if(!reti){ 
       puts("Match"); 
     } 
     else if(reti == REG_NOMATCH){ 
       puts("No match"); 
     } 
     else{ 
       regerror(reti, &regex, msgbuf, sizeof(msgbuf)); 
       fprintf(stderr, "Regex match failed: %s\n", msgbuf); 
       exit(1); 
     } 

/* Free compiled regular expression if you want to use the regex_t again */ 
    regfree(&regex); 

     return 0; 
} 

回答

2

要搜索的字符串abc,只需取下\b,即

reti = regcomp(&regex, "abc", 0); 

这将匹配,而"\babc\b"将只匹配abc包围与退格字符。只匹配abc(即123 abc 123,但不123 abc123123abc123),引用反斜线,如

reti = regcomp(&regex, "\\babc\\b", 0); 
+0

真棒人!谢谢! – ethanjyx

相关问题