正则表达式 练习:验证邮箱地址

来自姬鸿昌的知识库
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1Eq4y1E79W?p=24

验证电子邮件格式是否合法

规定电子邮件规则为:

  1. 只能有一个@
  2. @前面是用户名,可以是 a-z、A-Z、0-9、 _(下划线)、-(减号、中划线)字符
  3. @后面是域名,并且域名只能是英文字母,比如 sohu.com 或者 tsinghua.org.cn

写出对应的正则表达式,验证输入的字符串是否满足规则



自己实现的

public class Homework01 {

    public static void main(String[] args) {

        String regex = "[\\w-]+@([a-zA-Z]+\\.)+[a-zA-Z]+";

        Homework01 work = new Homework01();

        String content = "jihongchang@jihongchang.top";

        System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));

        content = "jihongchang@";

        System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));

        content = "jihongchang@jihongchang";

        System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));

        content = "jihongchang@jihongchang.";

        System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));

        content = "ji_hong-chang@jihongchang.top";

        System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));

        content = "ji_hong-chang@jihongchang.@jihongchang.top";

        System.out.printf("\"%s\".matches(regex):%b \n", content, content.matches(regex));

    }


    public boolean test1(String regex) {

        String content = "jihongchang@jihongchang.top";

        return content.matches(regex);

    }

    public boolean test2(String regex) {

        String content = "jihongchang@";

        return !content.matches(regex);

    }

    public boolean test3(String regex) {

        String content = "jihongchang@jihongchang";

        return !content.matches(regex);

    }

    public boolean test4(String regex) {

        String content = "jihongchang@jihongchang.";

        return !content.matches(regex);

    }

    public boolean test5(String regex) {

        String content = "ji_hong-chang@jihongchang.top";

        return content.matches(regex);

    }

    public boolean test6(String regex) {

        String content = "ji_hong-chang@jihongchang.@jihongchang.top";

        return content.matches(regex);

    }

}
"jihongchang@jihongchang.top".matches(regex):true 
"jihongchang@".matches(regex):false 
"jihongchang@jihongchang".matches(regex):false 
"jihongchang@jihongchang.".matches(regex):false 
"ji_hong-chang@jihongchang.top".matches(regex):true 
"ji_hong-chang@jihongchang.@jihongchang.top".matches(regex):false

注意:String matches 是整体匹配