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. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 weeks, 5 days ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 1 week ago

Comments

Please login first before commenting.