java kotlin正则表达式匹配邮箱

记录一下。
本代码,仅做一些简单的校验,并不会做特定场景的使用。比如并不考虑域名是大于2个字符的。
名字也可以以.结尾等。约束是比较宽的。

//val emailPattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
    val emailPattern = "^.+@.+\\.[A-Za-z]+$"
    val pattern: Pattern = Pattern.compile(emailPattern)

    val emails = arrayListOf<String>(
        "@",
        ".@.",
        ".@.",
        "@",
        "aa.net",

        "[email protected]",
        "[email protected]",
        "a@b.",
        "[email protected].",

        "@b.c.",

        "a@b",

        "01@02",
        "[email protected]",

        "a12",
        "c231.",

        "d123@",
        "@1a8",

        "中文@中文.com",
        "中文@中文",
        "中文@.com",
        "中文@a.y"
    )

    for (email in emails) {
        val matcher: Matcher = pattern.matcher(email)
        if (matcher.matches()) {
            println("Good!!! $email")
        } else {
            println("baad~~~  $email")
        }
    }

输出

 
baad~~~  @
baad~~~  .@.
baad~~~  .@.
baad~~~  @
baad~~~  aa.net
Good!!! [email protected]
Good!!! [email protected]
baad~~~  a@b.
baad~~~  [email protected].
baad~~~  @b.c.
baad~~~  a@b
baad~~~  01@02
Good!!! [email protected]
baad~~~  a12
baad~~~  c231.
baad~~~  d123@
baad~~~  @1a8
Good!!! 中文@中文.com
baad~~~  中文@中文
baad~~~  中文@.com
Good!!! 中文@a.y

你可能感兴趣的:(java,kotlin,正则表达式)