How to avoid greedy matching prior to the matched string?

Issue

This is the string that I want to test

"{{get}}","primary_object":null,"request_body_type":"JSON","request_body":[{"key":"name","value":"{{name.input}}{{input}}"

I want to match {{name.input}} (a string which ends with ".input}}" and begins with "{{") and I’m always getting the match that starts with {{get}}.
This is the regex I used – /{{.*input}}/g

Is there a regex that would match only this pattern – {{any_word_before_this.input}}

Solution

You could make the match for what preceeds .input less greedy by using a negative match on {..

That’s [^{.]: In the character group (or set) defined by [ characters ], start with ^ to make it match anything but the characters in the group.

Then use + for 1 or more of the matching characters:

/{{[^{.]+\.input}}/g

Answered By – Ted Lyngmo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published