python - 使用正则表达式在列表中查找与输入字符串匹配的单词
问题描述
想象一下,如果有一个单词列表 likewords = ["hello","boy","cool"]
和一个 string 的用户输入string = "helloboycool"
。
我的问题:有没有办法使用正则表达式来查找“单词”列表中与输入“字符串”的一部分匹配的所有单词。
例如:
list = ["123","hello","nice","red","boy"]
和input = "helloniceboy"
。输入字符串没有空格。
使用“输入”字符串作为正则表达式的搜索词,输出应该是["hello","nice","boy"]
列表形式的单词。
是的,我知道这可以通过简单的循环来完成。但是,我只是想解决我在办公室工作时遇到的问题。所以,向大家提出这个问题是值得的。 另外,感谢所有的答案。他们肯定是有用的见解。重叠就好
我对python中的正则表达式相当陌生。
解决方案
正则表达式用于在字符串中查找内容,而不是列表。
我建议遍历列表并检查每个单词是否在里面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]
推荐阅读
- git - 在 Git 中,当源分支历史已更改时,如何从功能分支中变基?
- c# - 如何在不使用 C# 循环的情况下打印我的名字 100 次?
- django - 只有管理员可以访问的页面
- localization - 如何在 nuxt-i18n 文本中包含链接
- c# - 如何使我在 C# 中为 VSTO 应用程序创建的自定义按钮和功能区在 Outlook (MS Office 365 ProPlus) 中可见?
- python - 删除数值前的字符串,但不删除如果在熊猫数据框列中包含邮政信箱地址或套房号?
- c - 为什么我的结果在第一次迭代后不会更新(?)
- reporting-services - 我可以在 SSRS 表达式中使用 WHERE 子句吗?
- javascript - 仅考虑字母和数字在基本字符串中查找句子
- python - 脚本通过python运行时如何捕获bash错误