我有样本查询
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'
请建议我正则表达式将处理上述两种情况
感谢
答案 0 :(得分: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')
答案 1 :(得分: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)))
答案 2 :(得分:0)
这部分:WHERE c.name like 'Hoder%' and c.name like 'Stock%'
相当于:WHERE False
列(如c.name
)无法同时从Hoder
和Stock
开始。
您可能打算使用OR
而不是AND
。