Summary of several usage of question mark in JS regular expression


The matching greedy pattern can be stopped by adding a question mark after the repeated characters, such as +?, *?, {2,3}.

var pattern=/\w{2,3}/;
/*Results "AAA"; there will be as many matches as possible in greedy mode,
So it matches three duplicate characters
var pattern2=/\w{2,3}?/;
*Results "AA"; after the question mark is added, the number of matching repetitions will be minimized,
*So it matched to two duplicate characters

Use?: to generate groups without numbers, such as

var pattern=/(ab)\w+(ba)/;
/*Results "ab_ "; matched characters are grouped by the first (AB)
var pattern2=/(?:ab)\w+(ba)/;
*Result "Ba_ "; for the first time, add?:, resulting in a
*There is no numbered group, so the character $1 matches is the second group,
*That is, the text content matched by the first number group (BA)

(? =) and (?!); zero width positive and negative assertions. Parentheses indicate that the right side of a position must match the right side of = or not match the characters after.

var pattern=/str(?=ings)ing/;
/*The first two results are ["string"], and the last two are null;
*Str (? = ings) ing / matches "string", the right side of the position after r must be followed by
*Upper ings; same as / string (? = s) / matches "string"; position after G
*The right side of must be followed by an S. "string_ X "also contains" string ", but
*The condition in brackets (? =...) is not satisfied
var pattern=/string(?!s)/;
/*(?!...) the right side of a position cannot have characters matching after,
*String (?! s) / match "string", "g" cannot be followed by "s"

When it represents the number of repetitions, it represents 0 or 1 repetitions