繁体   English   中英

在正则表达式 python 中使用单个模式子 function 替换字符串中的两个或多个字符

[英]Replace two or more character in a string using single pattern sub function in regular expression python

使用单个正则表达式模式替换无效的 email 地址字符。 将“At”、“at”替换为“@”,将“dot”替换为“.”

代码:

import re

email = "abc at xyz.com, abc At xyz.com, abc (at) xyz [dot] com"
pa = re.compile(r'(\s+[\(\[]*\s*at*\s*[\)\]]*\s+)',flags=re.IGNORECASE)
em = pa.sub(r'@',email)
print(em)

Output

abc@xyz.com, abc@xyz.com, abc@xyz [dot] com

预计 output

abc@xyz.com, abc@xyz.com, abc@xyz.com

我怎样才能用'.'替换'[dot]'?

要求用单一模式进行替换只会将问题推向另一个角落。 简而言之, re.sub的第二个参数可以是任意复杂度的 function,但是要求将 function 内联到一行似乎有些虚伪。

在这里,我们创建了一个re.sub ,它使用一个简单的字典来决定用什么来替换匹配项。

import re

email = "abc at xyz.com, abc At xyz.com, abc (at) xyz [dot] com"
pa = re.compile(r'\W*(at|dot)\W*', flags=re.IGNORECASE)
em = pa.sub(lambda m: {'dot': '.', 'at': '@'}[m.group(1).lower()], email)
print(em)

主要技巧是仅将字典键捕获到带括号的子表达式中,然后在.group(1)中可用。

演示: https://ideone.com/3Llu0i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM