Python 使用正则表达式或任何其他方式在字符串中匹配列表中的所有单词
我正在编写一个python脚本,其中必须用字符串匹配列表中给出的所有单词。名单可以尽可能长。但我找到了匹配任何字符的操作,但找不到匹配列表中所有单词的操作。比如说Python 使用正则表达式或任何其他方式在字符串中匹配列表中的所有单词,python,regex,Python,Regex,我正在编写一个python脚本,其中必须用字符串匹配列表中给出的所有单词。名单可以尽可能长。但我找到了匹配任何字符的操作,但找不到匹配列表中所有单词的操作。比如说 s = "This is a sample string" list = ["is", "sample"] // any operation such that re.search(r'',s) return correct result // I want that regular expression or approach
s = "This is a sample string"
list = ["is", "sample"]
// any operation such that re.search(r'',s) return correct result
// I want that regular expression or approach to do it.
像这样的
import re
string = "This is a sample string"
lst = ["is", "sample"]
for item in lst:
rx = re.compile(r"\b{}\b".format(item))
if rx.search(string):
print("'{}' is in the string".format(item))
这就产生了
'is' is in the string
'sample' is in the string
要选择哪些单词?中的所有单词list@danish,从您的问题文本中不清楚所有单词对您意味着什么。您可以使用类似/\bword\b/g的内容在列表中进行迭代。您可以将匹配项添加到数组中。到目前为止您尝试了什么?