【问题标题】:Does python's re.sub take an array as the input parameter?python的re.sub是否将数组作为输入参数?
【发布时间】:2012-08-20 10:47:45
【问题描述】:

根据http://www.php2python.com/wiki/function.preg-replace-callback/ re.sub 是 PHP 的 preg_replace_callback 的 python 等价物,但是 php 版本需要一个数组来匹配要匹配的字符串,所以你可以传递多个字符串,但是 re.sub 似乎只需要一个单个字符串。

这是对的还是我对python的了解不够?

【问题讨论】:

  • 检查official documentation;是不是说你可以通过列表?
  • 我已经检查过了,但是作为一个python新手我想确认一下,以防可能有另一个python库程序做同样的事情,在那种情况下,提到的网站是错误的。

标签: python regex arrays replace preg-replace-callback


【解决方案1】:

我知道的聚会迟到了,但是如果这是您想要封装到函数中的多步骤过程的要求,那么您可以通过 numpy vectorize 进行处理:

def EliminateAlpha(elem):
    return re.sub("[a-zA-Z]", "", elem)

ElimAlphaArray = np.vectorize(ElimateAlpha)

array_of_strings = ["3a1", "1b2", "1c", "d"]
print(ElimAlphaArray(array_of_strings))

['31' '12' '1' '']

当然也可以直接用re.sub函数变成vectorize:

ElimAlphaArr = np.vectorize(re.sub)
print(ElimAlphaArr("[a-zA-Z]", "", array_of_strings))

['31' '12' '1' '']

【讨论】:

    【解决方案2】:

    如果你想在数组上做,你可以使用列表推导,例如

    >>> array_of_strings = ["3a1", "1b2", "1c", "d"]
    >>> [re.sub("[a-zA-Z]", "", elem) for elem in array_of_strings]
    ["31", "12", "1", ""]
    

    虽然如果你使用复杂的表达式,你应该首先在模式上使用re.compile

    【讨论】:

    • 在 preg_replace_callback 中,第一个参数是一个包含不同搜索->替换模式的数组,而 elem 是一个包含一个或多个搜索->替换模式的字符串。
    • @vfclists,您可以使用一系列嵌套的 re.sub 来做到这一点(因为它们每个都返回一个字符串)。
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2020-04-02
      • 2020-12-23
      • 1970-01-01
      • 2017-07-07
      • 2019-09-24
      相关资源
      最近更新 更多