Login

Regular Expression Replace Template Filter

Author:
joshua
Posted:
February 28, 2007
Language:
Python
Version:
Pre .96
Score:
7 (after 7 ratings)

This will perform a regular expression search/replace on a string in your template.

{% load replace %} {{ mystring|replace:"/l(u+)pin/m\1gen" }}

If: mystring = 'lupin, luuuuuupin, and luuuuuuuuuuuuupin are lè pwn' then it will return: mugen, muuuuuugen, and muuuuuuuuuuuuugen are lè pwn

The argument is in the following format:

[delim char]regexp search[delim char]regexp replace
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import re 

from django import template
register = template.Library()

@register.filter
def replace ( string, args ): 
    search  = args.split(args[0])[1]
    replace = args.split(args[0])[2]

    return re.sub( search, replace, string )

More like this

  1. Image compression before saving the new model / work with JPG, PNG by Schleidens 4 days, 13 hours ago
  2. Help text hyperlinks by sa2812 1 month ago
  3. Stuff by NixonDash 3 months ago
  4. Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
  5. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks ago

Comments

Please login first before commenting.