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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.