【问题标题】:Is there a way to replace regexes dynamically in Python?有没有办法在 Python 中动态替换正则表达式?
【发布时间】: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)) 等价物吗?或者只是如何在 Python re.sub 中使用回调?
  • @WiktorStribiżew 我需要知道re.sub 部分,getenv 相当于os.getenv()

标签: php python regex python-3.x


【解决方案1】:

您可以将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 表示匹配数据对象。 USERGROUPm.group(1) 内部。

【讨论】:

    【解决方案2】:

    你好 user2064000,

    是的,python为正则表达式提供了许多内置函数。

    Re.sub(pattern, repl, string, count=0, flags=0)

    返回通过替换repl替换字符串中最左边不重叠出现的模式获得的字符串。如果未找到该模式,则字符串原样返回。 repl 可以是字符串或函数;如果它是一个字符串,则处理其中的任何反斜杠转义。也就是说,\n 转换为单个换行符,\r 转换为回车符,等等。诸如 \j 之类的未知转义将被单独留下。反向引用,例如 \6,被替换为模式中第 6 组匹配的子字符串。

    语法

    import re
    result = re.sub(pattern, callback, subject)
    result = re.sub(pattern, callback, subject, limit)
    

    有用的链接,
    https://docs.python.org/2/library/re.html

    解决方案

    import re, os
    
    def replaceFunction(matchobj):
         if matchobj.group(0) == "$USER":
        return os.getenv(matchobj.group(1))
         elif matchobj.group(0) == "$GROUP":
        return os.getenv(matchobj.group(1))
    
    print re.sub(r'\$([A-Za-z]+)', replaceFunction, 'foo:$USER:$GROUP')
    

    【讨论】:

    • 您好 user2064000 请检查我的回答。如果有用,请接受我的回答...
    【解决方案3】:

    你可以使用这样的东西:

    @classmethod
    def normalize_query_string(cls, query_string):
    
        def replace_fields(match):
            x = match.group("field")
            if x == "$certHash":
                return "ci.C.H:"
            return "{}:".format(x)
    
        result = re.sub(r"(?P<field>\$[\w.]+):", replace_fields, query_string)
        return result
    

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 2014-09-14
      • 2020-02-23
      • 2013-02-26
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多