1

嗨,我想用 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;
        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;
}
4

1 回答 1

2

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

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

这将匹配,而"\babc\b"仅匹配abc用退格符括起来的字符。要仅匹配单词 abc(即123 abc 123,但不匹配123 abc123or 123abc123),请引用反斜杠,如

    reti = regcomp(&regex, "\\babc\\b", 0);
于 2013-10-12T00:42:56.440 回答