美文网首页每天写500字每天写1000字
python 29:正则表达式的sub()方法

python 29:正则表达式的sub()方法

作者: 金石明镜 | 来源:发表于2019-12-14 21:25 被阅读0次

sub()方法有两个参数,第一个是用来替换的字符串,第二个是目标字符串,将用第一个参数替换第二个参数中的所有匹配项。

例1:

>>> namesRegex = re.compile(r'Agent \w+')

>>> namesRegex.sub('CENSORED','Agent Alice gave the secret documents to Agent Bob?')

'CENSORED gave the secret documents to CENSORED?'

在使用分组的情况下,用\1,\2,\3,...来指称各分组。

例2:

>>> agentNamesRegex = re.compile(r'Agent (\w)\w*')

>>> agentNamesRegex.sub(r'\1*****','Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')

'A***** told C***** that E***** knew B***** was a double agent.'

这个例子中,Agent (\w)\w*匹配前面第一个单词是Agent而第二个是任意单词的项,第二个单词的第一个字符是其第一个分组(这里只有一个分组)。在替换时,这个字符被保留下来,其余被替换为****。

相关文章

网友评论

    本文标题:python 29:正则表达式的sub()方法

    本文链接:https://www.haomeiwen.com/subject/ebuhnctx.html