Replace and inserting strings within .txt files with the use of regex

John S jstrickler at gmail.com
Sun Aug 8 04:56:05 CEST 2010


Even though I just replied above, in reading over the OP's message, I
think the OP might be asking:

"How can I use RE string replacement to find PHP tags and convert them
to Django template tags?"

Instead of saying

source_contents = source_contents.replace(...)

say this instead:

import re


def replace_php_tags(m):
   ''' PHP tag replacer
   This function is called for each PHP tag. It gets a Match object as
   its parameter, so you can get the contents of the old tag, and
should
   return the new (Django) tag.
   '''

   # m is the match object from the current match
   php_guts = m.group(1)  # the contents of the PHP tag

   # now put the replacement logic here

   # and return whatever should go in place of the PHP tag,
   # which could be '{{ python_template_var }}'
   # or '{% template logic ... %}
   # or some combination

source_contents = re.sub('<?\s*(.*?)\s*?
>',replace_php_tags,source_contents)









More information about the Python-list mailing list