在正则表达式中如何匹配多个 Or 条件但排除一个条件

in regex how to match multiple Or conditions but exclude one condition

如果我需要匹配字符串“a”及其前后符号@#$的任意组合,例如@a@、#a@、$a$等,但不是特定模式@a $。我怎样才能排除这个?假设组合太多,无法手动一一拼出。并且它不是其他 SO 答案中看到的负面前瞻或落后案例。

import re
pattern = "[#|@|&]a[#|@|&]"
string = "something#a&others"
re.findall(pattern, string)

目前模式 returns 结果如预期的那样像 '#a&',但也错误地 return 在要排除的字符串上。正确的模式应该 return [] on re.findall(pattern,'@a$')

我打算建议一个相当丑陋和复杂的带有环视的正则表达式模式。但是,您可以继续使用当前模式,然后使用列表理解来删除误报情况:

inp = "something#a&others @a$"
matches = re.findall(r'[@#&$]+a[@#&$]+', inp)
matches = [x for x in matches if x != '@a$']
print(matches)  # ['#a&']

您可以使用字符 class 列出所有可能的字符,并在匹配后使用单个负向回顾来断言不是 @a$ 直接向左。

请注意,您不需要字符 class 中的 |,因为它会匹配管道字符并且与 [#|@&]

相同
[#@&$]a[#@&$](?<!@a$)

Regex demo | Python demo

import re

pattern = r"[#@&$]a[#@&$](?<!@a$)"
print(re.findall(pattern,'something#a&others@a$'))

输出

['#a&']