【问题标题】:How to match any empty OR non alphabetic symbol (python re)如何匹配任何空或非字母符号(python re)
【发布时间】:2021-11-19 12:59:50
【问题描述】:

我想编写 python re 表达式来匹配诸如“apple”、“apple!”、“apple”之类的字符串。等等。但是我不想匹配像“apples”或“appler”这样的字符串。

如何做到这一点?如果我写 r"apple[,!.-]*",它也匹配 "apples"。

基本上我想匹配“苹果”+“字符串结尾或非字母符号”

【问题讨论】:

  • 应该这样做"apple\W"

标签: python-3.x python-re


【解决方案1】:

假设我们要匹配:

“苹果”+“字符串结尾或非字母符号”

虽然非字母符号表示所有字符,但不是字母,我们应该能够匹配apple;_-_>:Z这样的字符串,但不能匹配appleZ;_-_>:这样的字符串。也就是说,很可能等同于以下情况:任何以apple 开头的字符串,后跟除abc...xyzABC...XYZ 之外的任何其他字符

在你的情况下,即:接受["apple", "apple!", "apple."],拒绝["apples", "appler"]

我们有几个 RE 选项可以实现这一目标。根据Python Docs,一种选择可能是(?!...),称为否定前瞻断言。另一个可能是[^...],称为complementing

下面的代码为您的案例提供了一个相对简单的实现。

import re


def test_regex(list_should_match, list_should_NOT_match):
    regex = "^apple(?![a-zA-Z]).*$"       # lookahead.       recommended
    # regex="^apple[^a-zA-Z]*$"           # complementing.      works but less flexibility
    ptn = re.compile(regex)
    for str in list_should_match:
        if ptn.match(str) == None:
            return False
    for str in list_should_NOT_match:
        if ptn.match(str) != None:
            return False
    return True


# All cases you provided
list_should_match = ["apple", "apple!", "apple."]
list_should_NOT_match = ["apples", "appler"]
res = test_regex(list_should_match, list_should_NOT_match)
print("tests result:    %s" % ("PASS" if res else "X"))

# Some additional cases
list_should_match = ["apple;_-_>:Z", "apple,", "apple-",
                     "apple;", "apple[", "apple>123456789",
                     "apple123456789", "apple123456789ZZZ"]
list_should_NOT_match = ["appleZ;_-_>:", "appleABC", "appleZZZ;;;;"]
res = test_regex(list_should_match, list_should_NOT_match)
print("(additional)tests result:    %s" % ("PASS" if res else "X"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 2011-09-01
    相关资源
    最近更新 更多