带否定模式的Python正则表达式

2024-04-24 23:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python编写一个带有否定模式的regex语句。我想匹配一个模式,该模式不以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

下面是我尝试使用的regex语句:

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

Tags: andtheaddedgetis模式notspace
3条回答

看起来你想要[^U]W1?

您使用了一个包含“not?”,而不是标记“可选的1”。你知道吗

尝试regex模式([^U])W1?',并将其与re.sub()一起使用,同时使用引用捕获组的替换,如下所示:

import re

pattern = re.compile(r'([^U]W)1?')
for s in 'TUW1TH', 'JUWRG', 'BUIUW1', 'ATWKO', 'EWRG', 'AGDTWSD':
    print(pattern.sub(r'\1 ', s))

输出

TUW1TH
JUWRG
BUIUW1
ATW KO
EW RG
AGDTW SD

请注意,'EWRG'的输出与示例不同。。。我觉得你的问题有误?你知道吗

您的问题不清楚如何处理1后面的可选W,并且没有示例可供演示。是移除1还是保留?上述代码将丢失1

>>> print(pattern.sub(r'\1 ', 'TW1TH'))
TW TH

如果希望输出包含1,则可以将regex模式更改为r'([^U]W)(1?)',为可选的1添加第二个捕获组,并将替换更改为r\1 \2

>>> re.sub(r'([^U]W)(1?)', r'\1 \2', 'TW1TH')
'TW 1TH'

我认为您要求匹配的是可选的“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]在行首不起作用。你知道吗

相关问题 更多 >