删除重复模式(荷兰号码和邮政编码)正则表达式

2024-09-26 15:42:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python中的正则表达式删除重复项,但我有点挣扎

text= 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'
text = re.sub(r'\b(\d{,4})\s(\d{4})\s([A-Za-z]){2}\b', r'\1', text) 

print(text)

我想要“H.Gerhardstraat 77 1502 CC Zaandam”

我现在明白了: “H.Gerhardstraat 77 Zaandam”


Tags: textreccprintzazaandamgerhardstraat
2条回答

试试这个:

import re

c = re.compile(r'([\w\.]+)(?!.*\1)')
text = 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'

print(' '.join(c.findall(text)))

输出:

H. Gerhardstraat 77 1502 CC Zaandam

Link to Demo

解释:只有在以后使用否定前瞻断言没有任何相同的单词时,我们才将每个单词(包括句点)与[\w\.]+匹配\1这里指向([\w\.]+)

这样我们只得到列表中最后出现的单词

使用re.sub(pattern, repl, string, count=0, flags=0)的第四个参数count,如下所示:

text= 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'
pattern = r'(\d{0,4}\s\d{4}\s[A-Za-z]{2}\s+)'
count  = len(re.findall(pattern, text))

if count > 1:
    text = re.sub(pattern, '', text, count -1)

相关问题 更多 >

    热门问题