๐ฐgreedy vs. lazy
๐ง under construction
JS โฉ value โฉ object โฉ regex โฉ pattern โฉ repeat
quantifiers are
normally greedy (match as much as possible),
when followed by
?they become lazy (match as little as possible).
regex matches
------------------------------------------------------
+ b\w+ be bee beer beers (greedy)
โฐโฏ โฐโโฏ โฐโโโฏ โฐโโโโฏ
+? b\w+? be bee beer beers (lazy)
โฐโฏ โฐโฏ โฐโฏ โฐโฏ๐ฏ synonyms๏ผ "quantifier"
When using a repetition operator, consider the lazy variant first.
replit โฉ greedy vs. lazy
// greedy: [^]* or
// โ โญโโโฎ <--- greedy (as many as possible)
const commentPattern = /\/\/.*|\/\*[^]*\*\//g;
// โฐโ1โโโฏ โฐโโโโโ2โโโโโโฏ
// 1. '//' followed by any non-newline characters.
// 2. '/*' followed by any characters and '*/'.
// lazy: [^]*?
const commentPattern2 = /\/\/.*|\/\*[^]*?\*\//g;
// โฐโโโโฏ <--- lazy (as few as possible)
// remove comments from code
function stripComments(code, lazy = false) {
let pattern = commentPattern;
if (lazy) pattern = commentPattern2;
return code.replace(pattern, "");
}
stripComments("1 + /* 2 */ 3"), // '1 + 3'
stripComments("x = 10; // ten!"), // 'x = 10; '
stripComments("1 /* a */ + /* b */ 1"), // '1 1' // greedy
stripComments("1 /* a */ + /* b */ 1", true), // '1 + 1' // lazyLast updated
Was this helpful?