gpt4 book ai didi

php - 有没有办法在 Python 中动态替换正则表达式?

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:57 24 4
gpt4 key购买 nike

一些编程语言提供动态执行正则表达式替换的能力。

例如,假设我们有一个像 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 中有类似的东西吗?

最佳答案

您可以使用 re.sub使用 lambda 表达式或类似于 PHP 回调方法。

import re, os

s = 'foo:$USER:$GROUP'
rx = r'\$([A-Za-z]+)'
result = re.sub(rx, lambda m: os.getenv(m.group(1)), s)
print(result)

\$([A-Za-z]+) 模式匹配 $,然后将 1 个或多个 ASCII 字母捕获到第 1 组中。在 lambda 表达式中, m 表示匹配数据对象。 USERGROUP 位于 m.group(1) 内。

关于php - 有没有办法在 Python 中动态替换正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45836103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com