如何在“中使用正则表达式”;在;python函数
我使用Python的“in”函数来检查一个小字符串是否在另一个大字符串中。问题是接下来会发生什么:如何在“中使用正则表达式”;在;python函数,python,regex,string,Python,Regex,String,我使用Python的“in”函数来检查一个小字符串是否在另一个大字符串中。问题是接下来会发生什么: word1 = 'log' word2 = 'log_enable' string = ['parent_log', 'parent_log_enable'] for e in string: if word1 in e: print 'here we have the word' 所以,很明显,“我们有这个词”会被打印两次。我想知道是否可以在“in”函数中使用正则表达
word1 = 'log'
word2 = 'log_enable'
string = ['parent_log', 'parent_log_enable']
for e in string:
if word1 in e:
print 'here we have the word'
所以,很明显,“我们有这个词”会被打印两次。我想知道是否可以在“in”函数中使用正则表达式,在这种情况下,我应该使用哪一个来获得正确的输出
谢谢,谢谢
Mike.在中,不能将正则表达式与
一起使用。只需直接使用模块替换
中的:
import re
pattern = re.compile(r'log(?:_enable)?')
for e in string:
if pattern.search(e):
print 'here we have the word'
在这里,模式检查日志
,然后选择\u enable
您不能将正则表达式与一起使用。只需直接使用模块替换
中的:
import re
pattern = re.compile(r'log(?:_enable)?')
for e in string:
if pattern.search(e):
print 'here we have the word'
在这里,模式检查日志
,然后选择\u enable
您不能在
中单独使用来实现所需的功能
如果您想在
中使用,因为它更简洁,列表理解可能就是您想要的
我将以Martijn的答案为基础
重新导入
p=重新编译(r'log(?:\u enable)?)
#检查是否有匹配项
任何(p.在['parent\u log'、'parent\u log\u enable']中搜索s)
#结果:正确
#获得所有匹配项
[s代表['parent_log','parent_log_enable']中的s,如果p.search(s)]
#结果:['parent_log','parent_log_enable']
您不能在
中单独使用,以实现您的目标
如果您想在
中使用,因为它更简洁,列表理解可能就是您想要的
我将以Martijn的答案为基础
重新导入
p=重新编译(r'log(?:\u enable)?)
#检查是否有匹配项
任何(p.在['parent\u log'、'parent\u log\u enable']中搜索s)
#结果:正确
#获得所有匹配项
[s代表['parent_log','parent_log_enable']中的s,如果p.search(s)]
#结果:['parent_log','parent_log_enable']
中的不支持正则表达式。直接使用re
模块即可。如果您只测试两种可能性,您可以开始测试更长的可能性。为什么“显然”会打印两次?您的代码测试两个字符串,两个字符串都匹配。预期的结果是什么?您从未在此处测试过word2
。是的,我从未测试过word2,但'string'向量的每个单词中都有'log',因此打印结果会显示两次(两次,因为string vector有两个单元格)
中的不支持正则表达式。直接使用re
模块即可。如果您只测试两种可能性,您可以开始测试更长的可能性。为什么“显然”会打印两次?您的代码测试两个字符串,两个字符串都匹配。预期的结果是什么?你从来没有在这里测试过word2
。是的,我从来没有测试过word2,但是'log'在'string'向量的每个单词中,所以打印出来两次(两次,因为string向量有两个单元格)。谢谢,这是一个有趣的解决方案,但是Martijn的代码更适合mi脚本。再次感谢您不要在生成器表达式可用时使用列表理解。首先对所有输入执行p.search()
,然后让any()
测试结果。这违背了any()
的观点。谢谢,这是一个有趣的解决方案,但Martijn的代码更适合mi脚本。再次感谢您不要在生成器表达式可用时使用列表理解。首先对所有输入执行p.search()
,然后让any()
测试结果。这违背了any()
的观点。