> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/regex/pattern/repeat/greedy-vs.-lazy.md).

# greedy vs. lazy

🚧 under construction

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [object](/web/js/val/obj.md) ⟩ [regex](/web/js/val/builtin/regex.md) ⟩ [pattern](/web/js/val/builtin/regex/pattern.md) ⟩ repeat

{% hint style="success" %}
[**quantifiers**](/web/js/val/builtin/regex/pattern/repeat.md) are&#x20;

* normally <mark style="color:red;">**greedy**</mark> (match as <mark style="color:red;">**much**</mark> as possible),&#x20;
* when <mark style="color:orange;">**followed by**</mark> <mark style="color:yellow;">**`?`**</mark> they become <mark style="color:yellow;">**lazy**</mark> (match as <mark style="color:yellow;">**little**</mark> as possible).

```regex
     regex       matches
------------------------------------------------------
+    b\w+       be bee beer beers   (greedy)
                ╰╯ ╰─╯ ╰──╯ ╰───╯
+?   b\w+?      be bee beer beers   (lazy)
                ╰╯ ╰╯  ╰╯   ╰╯
```

:u6307: <mark style="color:yellow;">**synonyms**</mark>： "<mark style="color:purple;">**quantifier**</mark>"
{% endhint %}

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="warning" %}
When using a [**repetition operator**](/web/js/val/builtin/regex/pattern/repeat.md), consider the <mark style="color:yellow;">**lazy**</mark> variant <mark style="color:red;">**first**</mark>.
{% endhint %}
{% endtab %}

{% tab title="💈範例" %}

* replit ⟩ [greedy vs. lazy](https://replit.com/@pegasusroe/regex-greedy-vs-lazy#index.js)&#x20;

```javascript
// 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'     // lazy
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] Eloquent JavaScript ⟩ Regular Expressions ⟩ [Greedy](https://eloquentjavascript.net/09_regexp.html#h_kiECehz+i+)
* [ ] [Regular Expression Quick Reference](http://regexrenamer.sourceforge.net/help/regex_quickref.html)
  {% endtab %}
  {% endtabs %}
