gpt4 book ai didi

python - RegEx:如何匹配 Prefix + Shared OR Shared + Postfix?

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:08 27 4
gpt4 key购买 nike

假设我要匹配:

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_patternshared_pa​​tternpostfix_pattern 是文字字符串,请不要忘记使用 re.escape( )

关于python - RegEx:如何匹配 Prefix + Shared OR Shared + Postfix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46273355/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com