如何在下面的代码中搜索确切的单词“ dog”?我知道它的语法错误
#!/usr/bin/python
import re
list = ["dog", "do", "dog-dumb", "no_match", "dogs"]
var2 = 'dog'
for i in list:
match = re.search(^var2$, i)
if match:
print (match.group(0))
错误:
match = re.search(^var2$, i)
^
SyntaxError: invalid syntax
答案 0 :(得分:1)
如果您想搜索确切的单词dog
,那么为什么还要麻烦使用Regex?使用简单的等于运算符
#!/usr/bin/python
import re
list = ["dog", "do", "dog-dumb", "no_match", "dogs"]
var2 = 'dog'
for i in list:
if var2 == i:
print (i)
如果要进行不区分大小写的比较,请执行
if var2.lower() == i.lower()
编辑:
如果您仍然坚持使用正则表达式,请执行此操作
#!/usr/bin/python
import re
list = ["dog", "dodog", "dog-dumb", "no_match", "dogs"]
var2 = 'dog'
for i in list:
match = re.search("^"+var2+"$", i)
if match:
print (match.group(0))