First: the regular expression engine in JS, which defaults to greedy mode
We expect to match the words “witch” and “broom” in double quotes, but in fact we do match “witch” and her “broom”
let reg = /".+"/g;
let str = 'a "witch" and her "broom" is one';
console.log( str.match(reg) ); //"witch" and her "broom"
Copy the code
- Simply put: Here is a match
"
And then. +
It matches all the way to the end of STR, and then it matches back"
, so the final match did not meet expectations
Second: we need to turn on lazy matching
Add? Lazy and matching can be turned on, for example: +? , *? And????
let reg = /".+?" /g; let str = 'a "witch" and her "broom" is one'; console.log( str.match(reg) ); // witch, broomCopy the code
Third: instead of turning on lazy matching, we use an alternative
Use not ^ to match
let reg = /"[^"]+"/g;
let str = 'a "witch" and her "broom" is one';
console.log( str.match(reg) ); // witch, broom
Copy the code
Fourth: Alternative and lazy matching scenarios
In the following example we want to match , using lazy matching can be wrong
Using lazy matching is not the desired effect
let str1 = '... <a href="link1" class="wrong">... <p style="" class="doc">... '; let str2 = '... <a href="link1" class="doc">... <a href="link2" class="doc">... '; let reg = /<a href=".*?" class="doc">/g; console.log( str1.match(reg) ); // error!!!! <a href=\"link1\" class=\"wrong\">... <p style=\"\" class=\"doc\">" console.log( str2.match(reg) ); / / match right < a href = "\" link1 \ "class = \" doc \ ">", "< a href = \ \" link2 \ "class = \" doc \ ">"Copy the code
Use alternatives and match correctly
let str1 = '... <a href="link1" class="wrong">... <p style="" class="doc">... '; let str2 = '... <a href="link1" class="doc">... <a href="link2" class="doc">... '; let reg = /<a href="[^"]*" class="doc">/g; console.log( str1.match(reg) ); // No match, correct console.log(str2.match(reg)); // <a href="link1" class="doc">, <a href="link2" class="doc">Copy the code