Searching strings with Python
Question: I have the following sentence:

    
    
    Dave put the rubbish in the {{ if dave_good }}bin{{ else }}street{{ endif }}.
    

I'm currently replacing variables in text strings by capturing `[[ something
]]` and replacing the whole instance with a value _(not a problem)_. But
that's using python's `re` library.

I was wondering if someone could show me how to:

  1. search for single instances of `{{ if dave_good }}` in the string
  2. count forward from the `{{ if dave_good }}` to make sure there is a `{{ endif }}` before the end of the string
  3. if there is no `{{ else }}` then remove the tags, or the tags and their content, _(at their location in the text)_ based on the boolean attribute of `dave_good`
  4. if there is an `{{ else }}`
    1. if `dave_good` is `TRUE` then remove `{{ if dav_good }}` and `{{ else }}street{{ endif}}`
    2. if `dave_good` is `FALSE` then remove `{{ endif }}` and `{{ if dave_good }}bin{{ else }}`


Answer: try with [Regular Expressions](http://docs.python.org/2/howto/regex.html).

Example:

    
    
    import re
    
    result = re.match("\{\{((if|else|endif).*?)\}\}","{{if 100 > 1}}",re.I)
    print result.groups()
    
    result = re.match("\{\{((if|else|endif).*?)\}\}","{{else}}",re.I)
    print result.groups()
    
    result = re.match("\{\{((if|else|endif).*?)\}\}","{{endif}}",re.I)
    print result.groups()
    

Or use a template engine for python

  1. [jinja](http://jinja.pocoo.org/)
  2. [cheetah](http://www.cheetahtemplate.org/)
  3. [Templating](https://wiki.python.org/moin/Templating)
  4. [bottlepy](http://bottlepy.org/docs/dev/stpl.html)

Good Luck!

