[英]Calling a substitution function Regex Python
每当正则表达式与字符串myString匹配时,我都会使用以下代码来调用替换函数。 我的问题是我是否可以根据正则表达式与${STRING}
还是$STRING
匹配来调用其他替换函数?
def replace(match):
match = match.group()
if matched == ${STRING}
return os.getenv(match[1:],'')
elif matched == $STRING:
return something else
else:
return error
def main()
myString = "my string ${withcool} $stuff"
re.sub("\$.+|\$\{.+\}",replace,myString)
我认为您想提取变量并求值。
如果是这样,则无需调用其他函数来提取变量,只需使用括号(捕获组)来提取它。
喜欢:
def replace(match):
print match.groups()
s='my string ${withcool} ${withcool2} $stuff'
re.sub(r'\$\{(\w+)\}', replace, s)
它会给出:
('withcool',)
('withcool2',)
如您所见, 变量已被提取。
但是,如果要匹配两个或多个模式,将会有些复杂。
如果使用re.sub(r'\\$(\\w+)|\\$\\{(\\w+)\\}', replace, s)
, match.groups()
将为:
(None, 'withcool')
(None, 'withcool2')
('stuff', None)
您需要从元组中获取不是None
的元素。
顺便说一句,我建议使用\\w
代替.
当您使用贪婪的正则表达式时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.