【发布时间】:2017-08-23 09:39:42
【问题描述】:
一些编程语言提供动态执行正则表达式替换的能力。
例如,假设我们有一个类似foo:$USER:$GROUP 的字符串,其中$USER 和$GROUP 将被它们的环境变量替换。转换后的字符串看起来像foo:john:admin。为了解决这个问题,我们必须把所有匹配\$[A-Za-z]+的字符串都取出来,然后查找环境变量值。
在 PHP 中,如下所示:
<?php
preg_replace_callback(
# the regular expression to match the shell variables.
'/\$[A-Za-z]+/',
# Function that takes in the matched string and returns the environment
# variable value.
function($m) {
return getenv(substr($m[0], 1));
},
# The input string.
'foo:$USER:$GROUP'
);
Python中有没有类似的东西?
【问题讨论】:
-
你的PHP代码不正确,有一个未定义的
$m。必须是$matches -
@WiktorStribiżew 是的,在我的手机上输入了这个。现在已经修好了。
-
你需要知道 Python 中的
getenv(substr($m[0], 1))等价物吗?或者只是如何在 Pythonre.sub中使用回调? -
@WiktorStribiżew 我需要知道
re.sub部分,getenv相当于os.getenv()
标签: php python regex python-3.x