The four types of glances

The loop structure does not match any characters, only specific positions in the text. Also called zero-width assertion.

type Regular expression Conditions for a successful match Matching direction
Look around in positive order (? =)… The subexpression matches the text on the right From left to right
Negative order look around (? ! …). Subexpression does not match text on the right From left to right
Definitely look around in reverse order (? < =…). The subexpression matches the text on the left From right to left
Negative reverse look around (? <! …). The subexpression does not match the text on the left From right to left

Here are some debugging results for the Chrome console (version 99.0.4844.51), where the negation of reverse loop support is incomplete.

let str = "77abc88";

str.replace(/ (? =abc)/g."#"); // '77#abc88'
str.replace(/ (? ! 7) /."#"); // '77#abc88'
str.replace(/ (? <=abc)/g."#"); // '77abc#88'
str.replace(/ (? 
      ."#"); // '#77abc88'
Copy the code

Non-capture parentheses and capture parentheses

let str = "abc abaa bb";
str.match(/ (? :ab)+/g); // ['ab', 'ab']

str.replace(/ (? :ab)+/g."$1"); // '$1,c $1,aa bb'
str.replace(/(ab)+/g."$1"); // 'ab,c ab,aa bb'
Copy the code

As can be seen from the examples, (? :ab) does not catch and assign to $1, (ab) does catch and assign to $1.

In actual combat

Add thousandth separators to numeric strings, such as 123,456,0

let str = "1234560";

str.replace(/(\d)(? = (? :\d{3})+$)/g."$1");
Copy the code

The solution process is as follows:

  • No capture bracket matchThree consecutive numbers:(? :\d{3})
  • Capture bracket matchingThree consecutive digitsSingle digit before:(\d)(? :\d{3})
  • Join The Roundabout:(\d)(? = (? :\d{3})+$), including+ $N groups of consecutive 3 digit ending strings
  • Replacement:At $1,