2011-10-31 34 views
2

我從上面的查詢,我知道的單詞列表示例查詢寫正則表達式相當於LIKE語句查詢

select c.name , c.id from company c where 
c.name like 'Hoder%' and c.name like 'Stock%' amd c.name like 'Colour%' 
and c.name like '%Delete' and c.name like '%Regular' and c.name like '%Filler' 
and c.name like '%wipe%' and c.name like '%palce%' and c.name like '%double%', 
and c.name in ('IT', 'Wall', SpyCorp', 'Signal') 

,我在執行與正則表達式 表格上面的查詢我寫了一個正則表達式像

#for exact matching words 
pnexact = ['IT', 'Wall', SpyCorp', 'Signal'] 
regexact = [re.compile(r"\b%s\b" % word.lower()) for word in pnexact]#list of regex object 
#for words which are contain in the string eg: '%wipe%' ... 
pncontains = ['wipe','palce','double',] 
pnregexobj_contains = re.compile(r"%s" % '|'.join(pncontains)) #single regex object 

上述正則表達式工作正常,但我不能寫正則表達式,這將漢勒的話'Hoder%','Stock%','Color%' 的情況和案件%Delete','%Regular','%Filler' 請建議我正則表達式,其中,W生病手柄上述兩種情況

感謝

回答

1

.*更換%。例如,要匹配的話就像%Delete使用:

>>> import re 
>>> re.match(r'\b.*Delete\b', 'NoDelete') 
<_sre.SRE_Match object at 0x100456100> 
>>> _.group() 
'NoDelete' 
>>> re.match(r'\b.*Delete\b', 'Mismatch') 
+0

我寫了這個正則表達式reg = re.compile(r'(\。*)delete $')爲'%刪除'字符串以單詞delete.is結束嗎? – Shashi

+0

我不認爲你想反斜槓 - 逃避'''因爲它把它變成一個字面的'.'字符,但正確的正則表達式與LIKE'%Delete''等價的確實應該是'。*刪除$ ',或者只是'刪除$'。 –

+0

@ e.dan好吧 – Shashi

1
import re 
m = lambda regex: re.match(regex, name) 

m(r'.*Delete$') # name like %Delete 
m(r'Delete') # name like Delete% 
m(r'.*Delete') # name like %Delete% 

要找出是否name是字中的一個:

pnexact = ['IT', 'Wall', 'SpyCorp', 'Signal'] # use `set()` if the list is long 
name in pnexact # name in ('IT', 'Wall', 'SpyCorp', 'Signal') 

或者,如果你想使用正則表達式:

m(r"^(?:%s)$" % "|".join(map(re.escape, pnexact))) 
0

此零件:WHERE c.name like 'Hoder%' and c.name like 'Stock%'

相當於:WHERE False

A柱(像c.name)從HoderStock同時無法啓動。

您可能打算使用OR而不是AND