创建一个Python正则表达式regex,找到字符串中每个单词中不重复连续出现的所有辅音字母

2024-03-28 09:13:31 发布

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

例如,如果给出“快乐”这个词,我只想要“H”和“y”。在

如果给出'completed',我只想要'm'、'p'、'l'、's'、'h'、'd

我知道(\w)\2会找到重复的字符,并且(?)?一)

[b-df-hj-np-tv-z]将找到所有的辅音,但我如何组合它们?在


Tags: dfnptv字符hj辅音completed
3条回答
from re import findall
string = "Happy you!"
res    = []
for c in findall('[^aeiou]', string): 
    if c not in res:
        res.append(c)   

过滤出重复项并使用您所需的“re”模块。在

你可以用

(?=[b-df-hj-np-tv-xz])(.)(?!\1)(?<!\1\1)

展现为

^{pr2}$

但遗憾的是,^{}中不允许最后一行,因为lookbehind必须有固定的长度。但是^{}模块¹支持它

In [1]: import regex
In [2]: s=r'(?=[b-df-hj-np-tv-xz])(.)(?!\1)(?<!\1\1)'

In [3]: regex.findall(s, 'happy')
Out[3]: ['h']

In [4]: regex.findall(s, 'accomplished')
Out[4]: ['m', 'p', 'l', 's', 'h', 'd']

根据cheeseshop的描述,“最终将取代Python当前的re-module实现”。在

下面是一个可以使用的正则表达式:

([^aeiou])\1+|([^aeiou\s])

然后你就可以抓到第二组了

RegEx Demo

说明:

^{pr2}$

代码:

>>> for m in re.finditer(r'([^aeiou])\1+|([^aeiou\s])', "accomplished"):
...     print m.group(2)
...
None
m
p
l
s
h
d

相关问题 更多 >