Skip to main content
 首页 » 编程设计

具有否定模式的 Python 正则表达式

2024年10月24日28lvdongjie

我正在尝试使用否定模式在 Python 中编写正则表达式语句。我想匹配的模式不是以 U 开头,后跟 W 并且可以选择以 1 结尾。以下是一些示例。

TUW1TH > # regex does not get applied 
JUWRG > # regex does not get applied 
BUIUW1 > # regex does not get applied 
ATWKO > ATW KO # regex applies and space is added after the W 
EWRG > E WRG # regex applies and space is added after the W 
AGDTWSD > AGDTW SD # regex applies and space is added after the W 

下面是我尝试使用的正则表达式语句:

 re.sub(ur"[^U]W[^?1]", ur"W ", word) 

请您参考如下方法:

我认为您要求匹配“W”(可选)后跟“1”,但前提是“W”前面没有“U”。如果是这样的话,答案就是“消极回头看”:

import re 
 
testcases = ['TUW1TH', 'JUWRG', 'BUIUW1', 'ATWKO', 'EWRG', 'AGDTWSD', 'W1EF', 'EW1RG'] 
 
# The `(W1?)` part matches a 'W' with an optional '1'. The `(?<!U)` part  
#     matches the current position only if it wasn't a preceded by a 'U' 
pattern = re.compile(r'(?<!U)(W1?)') 
 
for s in testcases: 
    print(pattern.sub(r'\1 ', s)) 

输出:

TUW1TH 
JUWRG 
BUIUW1 
ATW KO 
EW RG 
AGDTW SD 
W1 EF 
EW1 RG 

注意:[^U] 在行首不起作用。