您好,我想检查字符串是否包含" abc"使用GNU正则表达式,我已尝试\b
和\w
,但它们都不起作用。
#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(®ex, "\wabc\w", 0);
reti = regcomp(®ex, "\babc\b", 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
/* Execute regular expression */
reti = regexec(®ex, "123abc123", 0, NULL, 0);
if( !reti ){
puts("Match");
}
else if( reti == REG_NOMATCH ){
puts("No match");
}
else{
regerror(reti, ®ex, 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(®ex);
return 0;
}
答案 0 :(得分:2)
要搜索字符串abc
,只需删除\b
,即
reti = regcomp(®ex, "abc", 0);
这将匹配,而"\babc\b"
仅匹配退格字符所附的abc
。要仅匹配字 abc
(例如123 abc 123
,而不是123 abc123
或123abc123
),请引用反斜杠,如
reti = regcomp(®ex, "\\babc\\b", 0);