如何检查字符串是否包含GNU正则表达式中的多个字符?

时间:2013-10-12 00:36:45

标签: regex

您好,我想检查字符串是否包含" 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(&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;
}

1 个答案:

答案 0 :(得分:2)

要搜索字符串abc,只需删除\b,即

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

这将匹配,而"\babc\b"仅匹配退格字符所附的abc。要仅匹配 abc(例如123 abc 123,而不是123 abc123123abc123),请引用反斜杠,如

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