Login

Regular Expression Replace Template Filter

Author:
joshua
Posted:
February 28, 2007
Language:
Python
Version:
Pre .96
Tags:
regex regular-expressions templates filters
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. Use MEDIA_URL in flatpages by robhudson 7 years ago
  2. @reply links in Twitter messages by ryanberg 6 years, 8 months ago
  3. Cheap direct_to_tempalte patterns by jjdelc 6 years, 4 months ago
  4. Template tag "ifregex" and "ifnotregex" by arthurfurlan 5 years, 10 months ago
  5. in_group template filter by whiteinge 6 years, 9 months ago

Comments

Please login first before commenting.