假设我们要匹配:
“苹果”+“字符串结尾或非字母符号”
虽然非字母符号表示所有字符,但不是字母,我们应该能够匹配apple;_-_>:Z这样的字符串,但不能匹配appleZ;_-_>:这样的字符串。也就是说,很可能等同于以下情况:任何以apple 开头的字符串,后跟除abc...xyz 和ABC...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"))