Regular matching problem

  node.js, question
 //Standardize url, remove query string and optional backslash
 var path = req.url.replace(/\/?  (?  :\?  .*)?  $/, '');

I encountered a regular expression (to match url) while studying node, and I don’t understand it a bit,/\/? (? :\? .*)? $/Inside
(? What does:) mean, isn’t the escape character placed after it, (:? Thank you!

Comments inside said very clearly is to remove the query string in the url


The question mark is not an escape character, and the’ \’ backslash is the escape character. There are several question marks here. I will explain them one by one.

The first is that there is a backslash in front of it, which indicates that this is the matching question mark itself.
Second: (? : exp), is to capture, match exp, does not capture the matching text, nor does it assign a group number to this group
The third is to match the question mark itself.
The fourth is a common qualifier, which means that the previous content is repeated zero or once.

Hope to help: ~)

Supplementary Knowledge: Common Grouping Grammar

Common grouping syntax includes 3 types:

  1. capture

  2. Zero width assertion

  3. Notes

Capture is divided into:
(exp): Match exp and capture text to automatically named group inside
(? < name>exp): match exp and capture the text to the group inside named name, or write (? ‘name’exp)
(? : exp): matches exp, does not capture matching text, and does not assign a group number to this group.

After capturing, you can use $1 or $name to refer to the capture, for example: taking we need to capture ing, we can use this method.


This captures ing, so we use js method replace to make some changes.

//here $1 is automatic grouping
 "taking".replace(/(ing)/, '$1 me');

But if you use it/(? :ing)/Then $1 won’t get the value, because there is no automatic grouping, other can be similarly deduced, you can try it yourself