2

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

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

4

3 回答 3

7

如果要在数组上执行此操作,可以使用列表推导,例如

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

虽然如果您使用的是复杂的表达式,您可能应该re.compile先在模式上使用

于 2012-08-25T01:30:29.593 回答
2

它只需要一个字符串http://docs.python.org/library/re.html#re.sub

于 2012-08-24T21:17:55.770 回答
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 函数用于向量化:

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

['31' '12' '1' '']
于 2018-03-17T01:48:52.653 回答