unexpected non-greedy JS regular expression result

javascript, regex

Solution

This can make you understand the role of the lazy operator:

/<.+?> e/.exec("a <b> c <d> e <f> e")` // -> ["<b> c <d> e", "<f> e"]
/<.+> e/.exec("a <b> c <d> e <f> e")`  // -> ["<b> c <d> e <f> e"]

`<.+?> e` means: once a `<` is found, find the first `> e`

`<.+> e` means: once a `<` is found, find the last `> e`

In your specific case, you could simply use `<[^>]+> e` (which is even better since quicklier - when its possible, always prefer the `X[^X]X` notation rather than the `X.*?X` one).

Problem

Why does ``` /<.+?> e/.exec("a <b> c <d> e") ``` (unexpectedly) return ``` ["<b> c <d> e"] ``` instead of ``` ["<d> e"] ``` The non-greedy operator seems to be doing nothing...

Original source