Python正则表达式校验某个字符串是否是合格的email

2023-07-24 19:46:44 浏览数 (1)

Python正则表达式校验某个字符串是否是合格的email

可以借助正则表达式校验某个字符串是否是合规的电子邮箱。对于邮箱的正则表达式有严格的模式,如:^[a-zA-Z0-9_ &*-] (?:\.[a-zA-Z0-9_ &*-] )*@(?:[a-zA-Z0-9-] \.) [a-zA-Z]{2,7}$ 对应的Python实现如下:

代码语言:javascript复制
import re;

REGEX_PATTERN = "^[a-zA-Z0-9_ &*-] (?:\.[a-zA-Z0-9_ &*-] )*@(?:[a-zA-Z0-9-] \.) [a-zA-Z]{2,7}$"

# 校验某个字符串是否是合格的email地址
def IsValidEmail(email):
    if (re.search(REGEX_PATTERN, email)):
        print("有效的email地址")
    else:
        print("无效的email地址")

if __name__ == '__main__':
    email = "rohit.gupta@mcnsolutions.net"
    IsValidEmail(email)

    email = "praveen@c-sharpcorner.com"
    IsValidEmail(email)

    email = "inform2atul@gmail.com"
    IsValidEmail(email)

    # valid email addresses
    email = "alice@example.com"
    IsValidEmail(email)
    email = "alice.bob@example.com"
    IsValidEmail(email)
    email = "alice@example.me.org"
    IsValidEmail(email)

    # invalid email addresses
    email = "alice.example.com"
    IsValidEmail(email)
    email = "alice..bob@example.com"
    IsValidEmail(email)
    email = "alice@.example.me.org"
    IsValidEmail(email)

运行结果如下图所示:

0 人点赞