Entry
Perl-like variable substitutions in a string
Jun 16th, 2004 22:39
extras, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 111, Glyn Webster
"""
Packages: text.regular_expressions
"""
""" Function `perlsub': Does Perl-like variable substitutions in a
string.
Glyn Webster <glyn@ninz.org.nz> 2021-04-26
"""
def perlsub(text, vars, pattern = r'\$(\w+)', fussy = 1):
""" Does Perl-like variable substitutions in a string.
text -- the string
vars -- a dictionary of varible name to value, typically 'var
()'
pattern -- the variable pattern. The variable must be in group 1.
Defaults to to Perl's "$name" style.
fussy -- if true variables not in 'dict' raise KeyError
(default)
if false variables not in `dict' are left alone
Note: "perlsub(text, dict, r'%\((\w+)\)s', 1)" == "text % dict"
"""
if fussy:
return re.sub(pattern, lambda m, v=vars: str(v[m.group(1)]), text)
else:
return re.sub(pattern, lambda m, v=vars: str(v.get(m.group(1)),
m.group(0)), text)
"""
This is a similar function that allows not only variables
but expressions embedded in the string.
ex. print ev("3 + 4 = <3 + 4>") # will print ==> '3 + 4 = 7'
import sys
print ev("First item of sys.path is < sys.path[0] >")
print ev("<sys #comment>, <%dir%>, <#234*765+34#>")
The tag and substitution function can be specified
for less fussy mode and other styles.
ex. print ev("ARGV = ${sys.argv}", "\$(\{)(.*?)\}") # Perl,shell style
print ev("ARGV = ${sys.AABBCC}", "\$(\{)(.*?)\}", _evlazy) # No
error
print ev("ARGV = ${sys.AABBCC}", "\$(\{)(.*?)\}", _evinfo) # Show
info
"""
import re, sys
def ev(s, pat="<(\W?)(.*?)\\1>", f=lambda x: str(eval(x.group(2)))):
return re.sub(pat, f, s)
def _evlazy(x): # replace with "" when the expression fails
try: return str(eval(x.group(2)))
except: return ""
def _evinfo(x): # Show error info if expression fails
try: return str(eval(x.group(2)))
except:
import traceback
ei = sys.exc_info()
return "<"+str(traceback.format_exception_only(ei
[0],ei[1])[0]).strip("\n")+">"