Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c++ - Why this regular expression will not compile?

I would like to use regular expression from here:

https://www.rfc-editor.org/rfc/rfc3986#appendix-B

I am trying to compile it like this:

#include <regex.h>
...
regex_t regexp;
if((regcomp(&regexp, "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?", REG_EXTENDED)) != 0){
    return SOME_ERROR:
}

But I am stuck with return value of regcomp:

REG_BADRPT

According to man it means:

Invalid use of repetition operators such as using * as the first character.

Similar meaning at this man:

?, * or + is not preceded by valid regular expression

I wrote parser using my own regular expression, but I would like to test this one too, since its officially in rfc. I do no intend to use it for validation though.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Oli Charlesworth suggested, you need to escape backslash \ for the question marks ?. See C++ escape sequences for more information.

test program

#include <regex.h>
#include <iostream>

void test_regcomp(char *rx){
 regex_t regexp;
 if((regcomp(&regexp, rx, REG_EXTENDED)) != 0){
    std::cout << "ERROR :" << rx <<"
";
 }
 else{
   std::cout <<  "   OK :"<< rx <<"
";
 }
}

int main()
{

  char *rx1 = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?" ;
  char *rx2 = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?" ;

   test_regcomp(rx1);
   test_regcomp(rx2);

   return 0;
}

output

ERROR :^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?
   OK :^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?

The ?in your regex is the source of the REG_BADRPT error. It gets converted to ?. If you replace it by \?, regcomp will be able to compile your regex.

"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?"

   OK :^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...