Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace %variables%

Tags:

python

regex

I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

{'search': 'replace',
 'foo':    'bar'}

And a string like this:

Foo bar %foo% % search %.

I'd like to replace each variable with it's equivalent text from the dictionary:

Foo bar bar replace.

My current regex fails, so here it is (key and value are from dictionary.items()):

 re.sub(r'%\d+' + key + '[^%]\d+%', value, text)

Any help would be appreciated, as this regex stuff is driving me nuts...

like image 702
Blender Avatar asked Jun 01 '11 19:06

Blender


3 Answers

If you're flexible with your syntax in your string, Python has a built in mechanism for that:

>>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'}
Hello, Blender, my name is Ken

Alternatively, if you want that syntax, I'd avoid regular expressions and just do this:

>>> vars = {'search': 'replace',
...  'foo':    'bar'}
>>> mystring = "Foo bar %foo% % search %."
>>> for k, v in vars.items():
...     mystring = mystring.replace('%%%s%%' % k, v)
... 
>>> print mystring
Foo bar bar % search %.
like image 171
Ken Kinder Avatar answered Oct 18 '22 22:10

Ken Kinder


If you want it in one statement, you could do the following (assuming s is the string and d is the dictionary):

re.sub(r"[%]\s*[^%]+\s*[%]",lambda k:d.get(k[1,-1].strip(),k),s)

This uses a function in the replacement part to get each value from the dictionary, and ignores if it is not in the dictionary.

Edit: fixed bug with unwanted whitespace appearing in lookup key

like image 37
murgatroid99 Avatar answered Oct 18 '22 22:10

murgatroid99


Maybe I'm missing something, but wouldn't the following regex just work?

re.sub(r'%\s?' + key + '\s?%', value, text)

The only thing that's a bit special are the optional spaces; they can be matched with \s?.

like image 2
alienhard Avatar answered Oct 18 '22 23:10

alienhard