我要匹配" 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;
}


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

最佳答案

尝试以下方法:

([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}»

关于c - C中的正则表达式无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23216730/

10-16 18:45