I have a sample string from which i have to extract values. Given Sample:
{#-- important parameters #}
{#@@ { 'var1': { 'title':'blah blah', 'type':'text', 'value':'def. text', 'maxlength':10 },
'var2': { 'title':'blah blah', 'type':'number', 'value':10, 'min':1, 'max':100 } } #}
{#@@ { 'var3': { 'title':'blah blah', 'type':'range', 'value':'3.0', 'min':1, 'max':10, step: '0.1' } } #}
{#-- normal parameters #}
{#@@ { 'var4': { 'title':'blah blah', 'type':'text', 'value':'def. text', 'required':'false' } } #}
{{Variable_1}}
{{Variable_2}}
{{Variable_3}}
I want to extract them as given below:
1 ) {#-- important parameters #} to "important parameters" - Regex which will only extract from this {#-- #}
2)
{#@@ { 'var1': { 'title':'blah blah', 'type':'text', 'value':'def. text', 'maxlength':10 },
'var2': { 'title':'blah blah', 'type':'number', 'value':10, 'min':1, 'max':100 } } #} to { 'var1': { 'title':'blah blah', 'type':'text', 'value':'def. text', 'maxlength':10 },
'var2': { 'title':'blah blah', 'type':'number', 'value':10, 'min':1, 'max':100 } }
--- regex which will only extract from this {#@@ #}
currently using :
/[^{\#\-]+(?=#\})/g for these templates {#-- normal parameters #} --- it is extracting values from both patterns i need to parse one pattern at a time.
/[^#@@]+(?=#\})/g for these templates
{#@@ { 'var1': { 'title':'blah blah', 'type':'text', 'value':'def. text', 'maxlength':10 }, 'var2': { 'title':'blah blah', 'type':'number', 'value':10, 'min':1, 'max':100 } } #}
--- it is extracting values from both patterns i need to parse one pattern at a time
Any help will be really appreciated. Thanks
A regex isn't able to dynamically parse a character string. Let me explain: it's not possible to capture a dynamically variable number of groups.
However, this regex can match the "title" group and the first "parameters" group:
/ {#--\s+(.*?)\s+#}\s+?{#@@\s+((?:.|\n)+?)\s+#} /gm
If you wan to match all {#@@ XXX #}groups, you must know in advance the maximum number of possible cases. IT can be done with a regex like this (in case of max two parameters):
/ {#--\s+(.*?)\s+#}\s+?{#@@\s+((?:.|\n)+?)\s+#}(?:\s+?{#@@\s+((?:.|\n)+?)\s+#})? /gm
Otherwise, you must do it in two steps:
{#@@ XXX #} by {#-- XXX #} in a global group{#@@ XXX #} parts.For further explanation, the first regex shown above can be splitted into two parts:
{#--\s+(.*?)\s+#} for capturing {#-- XXX #} in the group(1){#@@\s+((?:.|\n)+?)\s+#} for capturing {#@@ XXX #} in the group(2)