0

I am having a variable having a value something like this

var = '${home_${path}}'

I want a regex which detects ${ any content } recursively. That is, first I should match ${home_${path}} and then ${path}. I need this to evaluate the variable content by replacing ${..} with its actual content.

1
  • Is it possible for there to be more than one ${} in a string like ${home} ${path}? Commented Feb 8, 2013 at 5:26

1 Answer 1

1

I think you need a regular function here instead of a regular expression. The problem is that pure regular expressions can't match arbitrarily nested recursive patterns. So, they aren't much use for track matching openers and closers.

Instead, write a function to make a pass over the input string tracking the openers in a LIFO stack (just append to a regular python list) and then match closers as you find them (popping off the most recent corresponding opener):

import re

braces = re.compile(r'(\${)|(})')

def substitute(s, **env):
    openers = []
    pos = 0
    while 1:
        mo = braces.search(s, pos)
        if mo is None:
            break
        opener, closer = mo.groups()
        if opener:
            openers.append(mo.start())
            pos = mo.end() + 1
            continue
        start = openers.pop()
        end = mo.end()
        body = s[start+2 : end-1]
        s = s[:start] + env[body] + s[end:]
    return s


print substitute('Return to ${home_${path}} for further ${action}',
                 home_world='earth',
                 home_state='kansas',
                 path='state',
                 action='orders')
Sign up to request clarification or add additional context in comments.

1 Comment

Regex can count just fine, to a finite amount. ;-) If talking about formal regular expressions that is. Regex libs like .NET can really count (you can add and subtract with balancing groups).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.