Python Regex为什么没有找到所有的双字?

2024-06-28 11:37:19 发布

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

我需要匹配双字,但我的正则表达式工作不正常。在

L = "let's s?,play%3with,1symbols88,/symbols"
pattern = r'(\b\S+\b)[\d\s\.,-?\)\(!\/]+\b\1\b'
r = re.compile(pattern, re.IGNORECASE)
print(re.findall(r, L))

# Outputs: ['s']
# Expected: ['s','symbols']

https://regex101.com/r/frz8kQ/3


Tags: httpsrecomoutputspatternexpectedprintlet
2条回答

可以使用更基本的正则表达式和^{}

import re
from collections import Counter
text = "let's s?,play%3with,1symbols88,/symbols"

word_pattern = re.compile('[a-z]+', re.I)
word_counter = Counter(re.findall(word_pattern, text))
print([word for word, counter in word_counter.items() if counter > 1])
# ['symbols', 's']

另一个使用re.split()函数和Counter子类的一行程序:

import collections, re

L = "let's s?,play%3with,1symbols88,/symbols"
print([i for i,c in collections.Counter(re.split(r'[\d\W]+', L)).items() if c > 1])

输出:

^{pr2}$

相关问题 更多 >