Santanu Nandi
Santanu Nandi

Reputation: 177

RegEx: Extract substring from a string which may contain several number of '{' and '}'

`<html>
<head>
  <title>DailyHoroscope.com</title>
  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
    {if $contact['timezone']} 
     {assign var=local_tz value=$contact['timezone']} 
    {else} 
     {assign var=local_tz value='America/New_York'} 
    {/if} 
    {assign var=tracking_params value="utm_medium={$medium}&utm_source={$source}&utm_campaign={$campaign}"}
</head>
<body style="background:#fff;">
</body>
</html>`

In this code I need to get substrings inside {}. I am using this RegEx

/\{([^}]*)\}/mig

Its working fine in case of those types of substring which contains only one { and }. like

{if $contact['timezone']}

but incase of this string--->

{assign var=tracking_params value="utm_medium={$medium}&utm_source={$source}&utm_campaign={$campaign}"}

I am expecting the whole string as result, but its returning me

{assign var=tracking_params value="utm_medium={$medium},
{$source} and {$campaign}

and that is right because my regex is ending after getting the first '}' ; is there any way to get the string which will contain same number of '{' and '}' using regEx? What will be the RegEx ?

Upvotes: 4

Views: 100

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

Provided you only have 1 level of nested curly braces, you can use

\{((?:[^{}]*\{[^{}]*\})*[^}]*)\}

See demo

Matches:

if $contact['timezone']
assign var=local_tz value=$contact['timezone']
else
assign var=local_tz value='America/New_York'
/if
assign var=tracking_params value="utm_medium={$medium}&utm_source={$source}&utm_campaign={$campaign}"

Upvotes: 1

Related Questions