Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rege: find all individual words between double curly braces

My regex is pretty weak so I need some help. I have a case where I need to find all individual words between curly braces. I need a single regex to do the below use case. I cant post process the regex.

For example

Hi {{username}}, You total is {{ user.total - discount}}, please pay by date {{moment.utc(userPaymentDateTime)}}

The output here should be like

[username, user.total, - , discount, moment.utc,userPaymentDateTime]


I've Tried the following

\{{(.*?)\}}

Output is [username,user.total-discount,moment.utc(userPaymentDateTime)]

(?!{{)\s*(\w+)\s*(?=}})

Output is [username, discount]
like image 874
Mohit Agarwal Avatar asked Dec 17 '25 13:12

Mohit Agarwal


1 Answers

If you are using the ECMAScript 2018+ compliant JavaScript environment, you can use

(?<=\{\{(?:(?!\{\{|}}).)*)[^\s()]+(?=(?:(?!\{\{|}}).)*}})

See the regex demo. Details:

  • (?<=\{\{(?:(?!\{\{|}}).)*) - a positive lookbehind that requires the following sequence of patterns to occur immediately to the left of the current location:
    • \{\{ - a {{ string
    • (?:(?!\{\{|}}).)* - any char other than line break chars, zero or more times, that does not start a }} or {{ char sequences
  • [^\s()]+ - one or more chars other than whitespace, ( and )
  • (?=(?:(?!\{\{|}}).)*}}) - a positive lookahead that requires the following sequence of patterns to occur immediately to the right of the current location:
    • (?:(?!\{\{|}}).)* - any char other than line break chars, zero or more times, that does not start a }} or {{ char sequences
    • }} - a }} string.
like image 74
Wiktor Stribiżew Avatar answered Dec 19 '25 03:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!