匹配所有由逗号分隔的精确长度的单词

2024-04-20 00:48:47 发布

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

我有一个字符串,格式如下:

text = "Louis,Edward,John,Billy,Don,Dean"

我想从这个字符串中提取长度在2到4之间的所有名称。如果列表中只有一个名称,则没有逗号:

text = "Louis"

我试着用这个正则表达式:

import re
pattern = re.compile('(\w{2,4})(,\w{2,4})*')
search_result = pattern.findall('Louis,Edward,John,Billy,Don,Dean')
print(search_result)

结果是:

[('Loui', ''), ('Edwa', ''), ('rd', ',Bill'), ('Don', ',Dean')]

虽然我希望:

['John', 'Don','Dean']

我做错什么了?你知道吗


Tags: 字符串textre名称列表search格式result
3条回答

您也可以这样做:

text = "Louis,Edward,John,Billy,Don,Dean"
result = list(filter(lambda x:2<=len(x)<=4,text.split(",")))

You can try it here

修复regex,可以在\w{2,4}周围添加单词边界。你知道吗

re.findall(r'\b\w{2,4}\b', text)
# ['John', 'Don', 'Dean']

或者

p = re.compile(r'\b\w{2,4}\b')
p.findall(text)
# ['John', 'Don', 'Dean']

这将确保仅当名称长度2-4不是较大字符串的一部分时才匹配它们。你知道吗

RegEx似乎不需要执行此任务。您可以尝试使用逗号拆分字符串,然后使用列表进行筛选:

names = 'Louis,Edward,John,Billy,Don,Dean'

result = [name for name in names.split(',') if 2 <= len(name) <= 4]

['John', 'Don', 'Dean']

相关问题 更多 >