regex - Python re.sub question -


greetings all,

i'm not sure if possible i'd use matched groups in regex substitution call variables.

a = 'foo' b = 'bar'  text = 'find replacement me [[:a:]] , [[:b:]]'  desired_output = 'find replacement me foo , bar'  re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid re.sub('\[\[:(.+):\]\]','\1',text) #replaces value 'a' or 'b', not var value 

thoughts?

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

a = 'foo' b = 'bar'  text = 'find replacement me [[:a:]] , [[:b:]]'  desired_output = 'find replacement me foo , bar'  def repl(m):     contents = m.group(1)     if contents == 'a':         return     if contents == 'b':         return b  print re.sub('\[\[:(.+?):\]\]', repl, text) 

also notice ? in regular expression. want non-greedy matching here.

i understand sample code illustrate concept, example gave, simple string formatting better.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -