c中的正则表达式无法正常工作

时间:2014-04-22 10:19:13

标签: c regex

我想匹配" 16KQGN579677 PT "

这是我的尝试:

^([A-Z0-9]{2}+)([A-Z]{4}+)([0-9]{1,6}+)([ ]{0,5}+)([A-Z]{1,4}+).*" 

这是代码:

int main(int argc, char *argv[]){
    regex_t str;
    int reti;
    char msgbuf[100];

    /* need to match this circuit(16KQGN579677 PT) */

     reti=regcomp(&str,"^([A-Z0-9]{2}+)([A-Z]{4}+)([0-9]{1,6}+)([ ]{0,5}+)([A-Z]{1,4}+).*",  0);

       if( reti )
       { 
      fprintf(stderr, "Could not compile regex\n"); 
      exit(1);
       }

    /* need to match this circuit(16KQGN579677 PT) */

    reti = regexec(&str, "16KQGN579677 PT", 0, NULL, 0);
    if( !reti ){
           puts("Match");
           }
    else if( reti == REG_NOMATCH ){
            puts("No match");
           }
    else   {
           regerror(reti, &str, msgbuf, sizeof(msgbuf));
           fprintf(stderr, "Regex match failed: %s\n", msgbuf);
           exit(1);
           }
regfree(&regex);
    return 0;
}

代码中的正则表达式有什么问题?

1 个答案:

答案 0 :(得分:0)

请改为尝试:

([0-9]{2}\w+\s+[A-Z]{1,4})

Match the regular expression below and capture its match into backreference number 1 «([0-9]{2}\w+\s+[\w]{2})»
   Match a single character in the range between “0” and “9” «[0-9]{2}»
      Exactly 2 times «{2}»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match a single character that is a “word character” (letters, digits, and underscores) «[\w]{2}»
      Exactly 2 times «{2}»