首页 > 解决方案 > 使用正则表达式在列表中查找与输入字符串匹配的单词

问题描述

想象一下,如果有一个单词列表 likewords = ["hello","boy","cool"]和一个 string 的用户输入string = "helloboycool"

我的问题:有没有办法使用正则表达式来查找“单词”列表中与输入“字符串”的一部分匹配的所有单词。

例如: list = ["123","hello","nice","red","boy"]input = "helloniceboy"。输入字符串没有空格

使用“输入”字符串作为正则表达式的搜索词,输出应该是["hello","nice","boy"]列表形式的单词。

是的,我知道这可以通过简单的循环来完成。但是,我只是想解决我在办公室工作时遇到的问题。所以,向大家提出这个问题是值得的。 另外,感谢所有的答案。他们肯定是有用的见解。重叠就好

我对python中的正则表达式相当陌生。

标签: pythonregex

解决方案


正则表达式用于在字符串中查找内容,而不是列表。

我建议遍历列表并检查每个单词是否在里面string

words = ["123", "hello", "nice", "red", "boy"]
string = "helloboycool"
result = []
for word in words:
    if word in string:
        result.append(word)
print(result)

可以为此使用正则表达式,但我不建议这样做 - 这更清洁、更快。

这是一个版本list comprehension

words = ["123", "hello", "nice", "red", "boy"]
string = "helloboycool"
result = [word for word in words if word in string]

推荐阅读