tags:

views:

175

answers:

3

Greetings all,

I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables.

a = 'foo'
b = 'bar'

text = 'find a replacement for me [[:a:]] and [[:b:]]'

desired_output = 'find a replacement for me foo and bar'

re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid
re.sub('\[\[:(.+):\]\]','\1',text) #replaces the value with 'a' or 'b', not var value

thoughts?

+5  A: 

Sounds like overkill. Why not just do something like

text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')

?

Noufal Ibrahim
text is stored in the DB. I guess I could replace all the [[::]] values with %() values and that should work. I'll give it a try. Thanks!
netricate
this method depends on whether you know the position of [[:a:]] and [[:b:]].
ghostdog74
There are lots of issues but what the OP is trying to do is conceptually the same as string formatting.
Noufal Ibrahim
+3  A: 

You can specify a callback when using re.sub, which has access to the groups: http://docs.python.org/library/re.html#text-munging

a = 'foo'
b = 'bar'

text = 'find a replacement for me [[:a:]] and [[:b:]]'

desired_output = 'find a replacement for me foo and bar'

def repl(m):
    contents = m.group(1)
    if contents == 'a':
        return a
    if contents == 'b':
        return b

print re.sub('\[\[:(.+?):\]\]', repl, text)

Also notice the extra ? in the regular expression. You want non-greedy matching here.

I understand this is just sample code to illustrate a concept, but for the example you gave, simple string formatting is better.

Christian Oudard
thanks for the code! this is actually closer to what I was thinking.
netricate
I answered your question, but I think you were asking the wrong question. When appropriate, Please PLEASE use string formatting in preference to regular expressions. Noufal Ibrahim answered the question you should have asked.
Christian Oudard
A: 
>>> d={}                                                
>>> d['a'] = 'foo'                                      
>>> d['b'] = 'bar' 
>>> text = 'find a replacement for me [[:a:]] and [[:b:]]'
>>> t=text.split(":]]")
>>> for n,item in enumerate(t):
...   if "[[:" in item:
...      t[n]=item[: item.rindex("[[:") +3 ] + d[ item.split("[[:")[-1]]
...
>>> print ':]]'.join( t )
'find a replacement for me [[:foo:]] and [[:bar:]]'
ghostdog74
thanks for another look at this. very cool! :)
netricate