Regex 如何在GNU正则表达式中检查字符串是否包含多个字符?
您好,我想用GNU正则表达式检查字符串是否包含“abc”,我尝试了Regex 如何在GNU正则表达式中检查字符串是否包含多个字符?,regex,Regex,您好,我想用GNU正则表达式检查字符串是否包含“abc”,我尝试了\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; in
\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;
}
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
regex_t regex;
国际视网膜;
char-msgbuf[100];
/*编译正则表达式*/
//reti=regcomp(®ex,“\wabc\w”,0);
reti=regcomp(®ex,“\babc\b”,0);
if(reti){fprintf(stderr,“无法编译正则表达式”);退出(1);}
/*执行正则表达式*/
reti=regexec(®ex,“123abc123”,0,NULL,0);
如果(!reti){
看跌期权(“匹配”);
}
else if(reti==REG_NOMATCH){
看跌期权(“不匹配”);
}
否则{
regerror(reti,®ex,msgbuf,sizeof(msgbuf));
fprintf(stderr,“正则表达式匹配失败:%s\n”,msgbuf);
出口(1);
}
/*如果要再次使用正则表达式,请释放已编译的正则表达式*/
regfree(®ex);
返回0;
}
要搜索字符串abc
,只需删除\b
,即
reti = regcomp(®ex, "abc", 0);
这将匹配,而“\babc\b”
将只匹配带有退格字符的abc
。要仅匹配单词abc
(即123 abc 123
,但不匹配123 abc123
或123abc123
),请引用反斜杠,如中所示
reti = regcomp(®ex, "\\babc\\b", 0);