Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式或任何其他方式在字符串中匹配列表中的所有单词_Python_Regex - Fatal编程技术网

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

我正在编写一个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 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的内容在列表中进行迭代。您可以将匹配项添加到数组中。到目前为止您尝试了什么?