POSIX正则表达式忽略非ascii字符?

时间:2013-10-12 03:02:00

标签: regex

我想检查字符串是否包含|c,但是一些非ascii字符会出现问题,因为以下代码返回Match。有没有办法忽略非ascii字符?

#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, "\|c", REG_EXTENDED);
        if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }

/* Execute regular expression */
        reti = regexec(&regex, "<81>U¼T_<84>Ùe/^P^Rï+߶ë", 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 :(得分:4)

输入中的非ASCII字符不是问题。相反,"\|c"是一种错误的写"|c"(匹配所有内容)的方式。使用两个反斜杠(一个用于转义字符串本身的反斜杠):

    reti = regcomp(&regex, "\\|c", REG_EXTENDED);
相关问题