Summary of several usage of question mark in JS regular expression

Time:2020-5-26

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}/;
console.log("aaaa".match(pattern)[0]);
/*Results "AAA"; there will be as many matches as possible in greedy mode,
So it matches three duplicate characters
*/
var pattern2=/\w{2,3}?/;
console.log("aaaa".match(pattern2)[0]);
/*
*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)/;
console.log("abcba_".replace(pattern,"$1"));
/*Results "ab_ "; matched characters are grouped by the first (AB)
*Replace
*/
var pattern2=/(?:ab)\w+(ba)/;
console.log("abcba_".replace(pattern2,"$1"));
/*
*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/;
console.log("strings.a".match(pattern));
console.log("strings.a".match(/string(?=s)/));
console.log("string_x".match(pattern));
console.log("string_x".match(/string(?=s)/));
/*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)/;
console.log("strings".match(pattern));//null
console.log("string.".match(pattern));//["string"]
/*(?!...) 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