使用正则表达式删除重复项

问题描述 投票:-3回答:1

嗨,我想从字符串中删除重复项。例如:

"Q. no. -320/2/2, Road no 25, Adityapur, Transport colony,  ADITYAPUR"

在上面的例子中,"Adityapur"重复两次。所以我想删除它。我怎么能用正则表达式做到这一点。

我正在使用这个正则表达式:

re.sub(r'\b(\w+)( \1\b)+', r'\1', s)

但它也删除了所有重复的字母。

python regex
1个回答
0
投票

正则表达式版本:

import re
s = "Q. no. -320/2/2, Road no 25, Adityapur, Transport colony,  ADITYAPUR"
s = s.lower()
re.split('; |, ',str)
m = [x.strip() for x in m]

sen = []
temp = []
for x in m:
    if x not in sen:
        sen.append(x)

free = ' '.join(sen)
print(free)
© www.soinside.com 2019 - 2024. All rights reserved.