我需要像下面这样匹配模式:AAXX#
其中:
* AA
来自一个集合(即1-3个字符阿尔法前缀的list
),
* XX
来自不同的预定义字符串列表,以及
* any single-digit numeral
跟随。
AA字符串:['bo','h','fr','sam','pe']
XX字符串:cl
+ ['x','n','r','nr','eaner]
//或者就是// ro
Desired Result: bool,指示是否有任何可能的组合与提供的字符串匹配。
测试字符串示例:
item = "boro1"
-即bo
+ ro
+ 1
item = "samcl2"
-即sam
+ cl
+ 2
item = "hcln3"
-即h
+ cln
+ 3
我能想到的最好的方法是使用一个循环,但是我在使用基本的正则表达式时遇到了麻烦。它适用于单字母可选的cln, clx, clr
,但不适用于较长的clnr, cleaner
。
代码:
item = "hclnr2" #h + clnr + 2
out = False
arr = ['bo','h','fr','sam','pe']
for mnrl in arr:
myrx = re.escape(mnrl) + r'cl[x|n|r|nr|eaner]\d'
thisone = bool(re.search(myrx, item))
print('mnrl: '+mnrl+' - ', thisone)
if thisone: out = True
##########################################################################
# SKIP THIS - INCLUDED IN CASE S/O HAS A BETTER SOLUTION THAN A SECOND LOOP
# THE ABOVE FOR-LOOP handled THE CL[opts] TESTS, THIS LOOP DOES THE RO TESTS
##########################################################################
#if not out: #If not found a match amongst the "cl__" options, test for "ro"
# for mnrl in arr:
# myrx = re.escape(mnrl) + r'ro\d'
# thisone = bool(re.search(myrx, item))
# print('mnrl: '+mnrl+' - ', thisone)
# if thisone: out = True
##########################################################################
print('result: ', out)
打印:
mnrl: bo - False
mnrl: h - False <======
mnrl: fr - False
mnrl: sam - False
mnrl: pe - False
但是,将item
更改为:
item = "hcln2" #h + cln + 2
打印:
mnrl: bo - False
mnrl: h - True <========
mnrl: fr - False
mnrl: sam - False
mnrl: pe - False
同样适用于item = hclr5
或item = hclx9
,但不适用于hcleaner9
https://stackoverflow.com/questions/52935405
复制相似问题