slevithan / xregexp

Extended JavaScript regular expressions
http://xregexp.com/
MIT License
3.31k stars 278 forks source link

PCRE-style group name #301

Closed alexwenbj closed 4 years ago

alexwenbj commented 4 years ago

In PCRE, it accepts (?P<name>...) as group naming style, can this lib be compatible with it?Thank you.

slevithan commented 4 years ago

XRegExp already supports (?P<name>...). It is not officially documented because, like in PCRE and Perl, it is not the preferred syntax (that syntax actually comes from Python).

Note that for named backreferences, XRegExp supports only \k<name>.

alexwenbj commented 4 years ago

Got it. Thank you.

alexwenbj commented 4 years ago

@slevithan Sorry to bother you again, but when I try this feature, it seems not work.

var t = XRegExp.exec('GET /downloads/product_1 HTTP/1.1', /(\w{3,}) (?P<url>.+) (HTTP\/[1|2]\.[0|1])/);
console.log(t);

it raised an error: Uncaught SyntaxError: Invalid regular expression: /(\w{3,}) (?P<url>.+) (HTTP\/[1|2]\.[0|1])/: Invalid group What is the problem with my code? Thank you.

slevithan commented 4 years ago

You’re trying to use (?P<name>...) in a regex literal — this doesn’t work because JavaScript doesn’t natively support it. You need to pass your regex pattern as a string to XRegExp, and escape the backslashes.

XRegExp.exec('...', XRegExp('(\\w{3,}) (?P<url>.+) (HTTP\\/[1|2]\\.[0|1])'));

Also, I think you mean to use [12] and [01], not [1|2] etc. (unless you really mean to allow matching a | character in that position).

alexwenbj commented 4 years ago

Got it . Thank you for your kindness. @slevithan