假设我要匹配:
PREFIXsomething
或:
somethingPOSTFIX
但肯定不是:
PREFIXsomethingPOSTFIX
其中 something 是某种共享模式,而 PREFIX/POSTFIX 实际上也是某些不同的模式。
我可以(或认为)用 Python 解决这个问题。但是,此构造适用于“PREFIXabc”但不适用于“abcPOSTFIX”。如何解决?
import re
prefix_pattern = "PREFIX"
postfix_pattern = "POSTFIX"
shared_pattern = "[a-zA-z]*"
test_pattern ="("+prefix_pattern+shared_pattern+")|("+shared_pattern+postfix_pattern+")$"
pattern = re.compile(test_pattern)
#test = 'PREFIXabc' # Match
test = 'abcPOSTFIX' # No match
x = re.match(pattern,test)
if x:
print(x.group())
else:
print("Not found")
请注意,当与 re.match
一起使用时,您的模式遵循类似 ^(alternative1)|^(alternative2)$
的方案。这意味着字符串 anchor 的 $
结尾只会影响第二个选择,如果 test = 'PREFIXabc123'
, PREFIXabc
will get matched .
根据您的要求,有两种方法可以解决。
要么您需要删除 $
,然后您还要匹配 test = 'abcPOSTIFX123'
中的 abcPOSTFIX
,或者将两个备选方案分组:
test_pattern=r"(?:{0}{1}|{1}{2})$".format(prefix_pattern, shared_pattern, postfix_pattern)
然后,将不再找到部分匹配项。
仅供引用:如果 prefix_pattern
、shared_pattern
和 postfix_pattern
是文字字符串,请不要忘记使用 re.escape( )
。
我是一名优秀的程序员,十分优秀!