Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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_String_Search - Fatal编程技术网

Python正则表达式搜索仅查找第一个模式

Python正则表达式搜索仅查找第一个模式,python,regex,string,search,Python,Regex,String,Search,我使用python的re模块在字符串中搜索某些单词 举个简单的例子,我有一个名为valid_words的列表和一个名为valid_string的字符串 valid_string = "Use Use%" valid_words = ['Use', 'Use%'] for header in valid_words: regex_search = re.search("\\b"+header+"\\b", valid_string) if regex_search: print

我使用python的re模块在字符串中搜索某些单词

举个简单的例子,我有一个名为valid_words的列表和一个名为valid_string的字符串

valid_string = "Use Use%"
valid_words = ['Use', 'Use%']

for header in valid_words:
  regex_search = re.search("\\b"+header+"\\b",  valid_string)
  if regex_search:
    print header

但是,这只返回Use,而不返回Use%。我认为这是因为“Use%”中的%被视为正则表达式。我说得对吗?有没有办法解决这个问题?

这里的问题是你在使用单词边界,但是,在你的第二个单词
'Use%'
中,单词边界实际上出现在
e
%
之间。例如:

>>> re.search('.\\b','Use%').group(0)
'e'

哦,我明白了。那么,有没有办法将有效单词的边界移到每个单词的末尾呢?@Fsun——很难说在这里最好做什么。看起来像是一个简单的
str.split
就是你想要的,但是很难说…谢谢。但是,str.split在我的情况下是不可行的。例如,有效_单词中的元素可能是“He llo”,因此正则表达式搜索将在有效_字符串中查找“He llo”。