【问题标题】:in regex how to match multiple Or conditions but exclude one condition在正则表达式中如何匹配多个或条件但排除一个条件
【发布时间】:2021-03-03 03:32:57
【问题描述】:

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

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

目前,该模式按预期返回类似 '#a&' 的结果,但也错误地返回要排除的字符串。正确的模式应该返回 [] on re.findall(pattern,'@a$')

【问题讨论】:

  • 您在这里期望/接受的所有符号是什么?

标签: python regex python-re


【解决方案1】:

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

请注意,您不需要在字符类中使用 |,因为它会匹配管道字符并且与 [#|@&] 相同

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

Regex demo | Python demo

import re

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

输出

['#a&']

【讨论】:

  • 不错的解决方案。不知道后视可以在它之后什么都不工作@第四只鸟
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多