Python string.replace equivalent (from Javascript) -
i trying pick python , coming javascript haven't been able understand python's regex package re
what trying have done in javascript build very simple templating "engine" (i understand ast way go more complex):
in javascript:
var rawstring = "{{prefix_helloworld}} testing this. {{_thiswillnotmatch}} \ {{prefix_okay}}"; rawstring.replace( /\{\{prefix_(.+?)\}\}/g, function(match, innercapture){ return "one rule all"; });
in javascript result in:
"one rule testing this. {{_thiswillnotmatch}} 1 rule all"
and function called twice with:
innercapture === "helloworld" match ==== "{{prefix_helloworld}}"
and:
innercapture === "okay" match ==== "{{prefix_okay}}"
now, in python have tried looking docs on re package
import re
have tried doing along lines of:
match = re.search(r'pattern', string) if match: print match.group() print match.group(1)
but doesn't make sense me , doesn't work. one, i'm not clear on group() concept means? , how know if there match.group(n)... group(n+11000)?
thanks!
python's re.sub
function javascript's string.prototype.replace
:
import re def replacer(match): return match.group(1).upper() rawstring = "{{prefix_helloworld}} testing this. {{_thiswillnotmatch}} {{prefix_okay}}" result = re.sub(r'\{\{prefix_(.+?)\}\}', replacer, rawstring)
and result:
'helloworld testing this. {{_thiswillnotmatch}} okay'
as groups, notice how replacement function accepts match
argument , innercapture
argument. first argument match.group(0)
. second 1 match.group(1)
.
Comments
Post a Comment