使用re.match()查找Substring

时间:2013-04-02 09:16:33

标签: python regex string

如何在不使用复杂正则表达式的情况下搜索空格分隔的字符串 这是我的代码

import re
stringToQueryLevel1 = ['why this','why this code','why this code is complex']  
for i in range(stringToQueryLevel1.__len__()):
    if re.search('why this' , stringToQueryLevel1[i]) != None:
        rc = 0
    else:
        rc = 1

    print rc 

2 个答案:

答案 0 :(得分:2)

非常简单

stringToQueryLevel1 = ['why this', 'why this code', 'why this code is complex']
for item in stringToQueryLevel1:
    print ' ' in item

答案 1 :(得分:0)

请尝试以下代码:

import re
stringToQueryLevel1 = ['why this','why this code','why this code is complex','TestTest'] 
for i in range(stringToQueryLevel1.__len__()): 
    if re.search('(\w+)\s(\w+)' , stringToQueryLevel1[i]) != None:
        print 'match found in %s'%(stringToQueryLevel1[i])
    else:
        print 'match not found in %s'%(stringToQueryLevel1[i])