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

use*_*000 4 php python regex python-3.x

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

例如,假设我们有一个像foo:$USER:$GROUP, where$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'
);
Run Code Online (Sandbox Code Playgroud)

Python中有类似的东西吗?

Wik*_*żew 9

您可以使用re.sublambda 表达式或类似于 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)
Run Code Online (Sandbox Code Playgroud)

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