Skip to content

Instantly share code, notes, and snippets.

@wrunk
Created December 3, 2012 22:11
Show Gist options
  • Save wrunk/4198592 to your computer and use it in GitHub Desktop.
Save wrunk/4198592 to your computer and use it in GitHub Desktop.
Python regular expressions cheatsheet
import re
# ---------------------------------------------------------------------------- #
# Regex sting substitution
#
# As a first example, lets say we have a jinja2 template that needs
# a particular section(s) replaced
LEFT_NAV = re.compile(r'{{\s*left_nav\s*}}')
def replace_left_nav(template_contents):
''' Pass me an unrendered block of content, and i will replace:
{{ left_nav }} with {% include "left_nav.html" %}
'''
# Since we already compiled our LEFT_NAV regex above, we use that in place
# of re.sub. First param is what you will put in place of LEFT_NAV, and
# finally the long string to look through for matches.
# Note this will replace all instances it finds. You can specify a
# parameter count to the sub function to limit this. Also see:
# http://docs.python.org/2/library/re.html
new_contents = LEFT_NAV.sub('{% include "left_nav.html" %}', template_contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment