Regex – Fixing Non-Greedy Match Being Too Greedy

regex

I have a regex pattern that needs to capture the shortest matches, but the lazy match isn't working in cases where that pattern is nested. Here's what I mean:

Regex pattern:

/{{.*?}}/

Example string:

{{This}} is {{an example {{sentence}}}}

In the above example, I'm expecting to pull {{This}} and {{sentence}}, as these are the shortest matches, but instead I am getting {{This}} and {{an example {{sentence}}. Why is the non-greedy match still being so greedy – or rather, where am I going wrong?

Best Answer

Try: {{[^{]*?}} This is using the fact that the '{' character should not appear in the inner strings. It does match what you expect.