用于替换句子中特定数字的正则表达式

问题描述 投票:0回答:1

我有一个类似下面的句子

test_str = r'Mr.X has 23 apples and 59 oranges, his business partner from Colorado staying staying in hotel with phone number +188991234 and his wife and kids are staying away from him'

我想将上面句子中的所有数字替换为'0',并且电话号码的第一位数字应为+1。

result = r'Mr.X has 00 apples and 00 oranges, his business partner from Colorado staying staying in hotel with phone number +1******** and his wife and kids are staying away from him'

我有以下正则表达式来替换电话号码格式(始终具有一致的数字)。

result = re.sub(r'(.*)?(+1)(\d{8})', r'\1\2********', test_str)

我可以在一个正则表达式中用电话号码以外的其他数字替换为0吗?

python regex string re
1个回答
0
投票
我们可以将re.sub与功能一起使用

要替换电话号码,请在下面使用正则表达式。+1后跟的所有数字将替换为*

的等价数字

result = re.sub(r'(?<!\w)(\+1)(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)

为了将其他数字替换为0,可以在下面使用正则表达式,所有不带+或数字的数字都将替换为等价的数字0

result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), test_str)

示例

>>> test_str = r'Mr.X has 23 apples and 59 oranges, his phone number +188991234' >>> result = re.sub(r'(?<!\w)(\+1)(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str) >>> result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), result) >>> result 'Mr.X has 00 apples and 00 oranges, his phone number +1********'

© www.soinside.com 2019 - 2024. All rights reserved.