删除重复模式(荷兰号码和邮政编码)REGEX
Remove duplicate pattern (dutch number and postal code) REGEX
我想在 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'', text)
print(text)
我想得到'H. Gerhardstraat 77 1502 CC Zaandam'
我现在明白了:
'H. Gerhardstraat 77 77 Zaandam'
使用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)
试试这个:
import re
c = re.compile(r'([\w\.]+)(?!.*)')
text = 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'
print(' '.join(c.findall(text)))
输出:
H. Gerhardstraat 77 1502 CC Zaandam
解释 :只有当后面没有任何相同的词时,我们才会匹配每个词,包括句点 [\w\.]+
使用 negative lookahead assertion。 </code>这里指向<code>([\w\.]+)
组。
这样我们只得到列表中最后一次出现的单词。
我想在 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'', text)
print(text)
我想得到'H. Gerhardstraat 77 1502 CC Zaandam'
我现在明白了: 'H. Gerhardstraat 77 77 Zaandam'
使用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)
试试这个:
import re
c = re.compile(r'([\w\.]+)(?!.*)')
text = 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'
print(' '.join(c.findall(text)))
输出:
H. Gerhardstraat 77 1502 CC Zaandam
解释 :只有当后面没有任何相同的词时,我们才会匹配每个词,包括句点 [\w\.]+
使用 negative lookahead assertion。 </code>这里指向<code>([\w\.]+)
组。
这样我们只得到列表中最后一次出现的单词。