正则表达式匹配邮箱

正则表达式匹配邮箱

使用 java.util.regex 包中的正则表达式工具类 Pattern 和 Matcher 来匹配邮箱地址。下面是一个示例代码:

import java.util.regex.*;

public class EmailValidation {
  public static void main(String[] args) {
    String email = "example@gmail.com";
    String regex = "^([\\w-]+(\\.[\\w-]+)*)@[\\w-]+(\\.[\\w-]+)+$";

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(email);

    if (matcher.matches()) {
      System.out.println("Valid email address.");
    } else {
      System.out.println("Invalid email address.");
    }
  }
}
  • 在这个示例中,我们定义了一个邮箱地址 example@gmail.com 和一个匹配邮箱地址的正则表达式 ^([\w-]+(.[\w-]+)*)@[\w-]+(.[\w-]+)+$。
  • 然后,我们使用 Pattern 类的 compile 方法将正则表达式编译成一个模式对象,再使用 Matcher 类的 matcher 方法将模式对象和邮箱地址进行匹配。
  • 最后,使用 Matcher 类的 matches 方法检查邮箱地址是否与模式匹配。

需要注意的是,在 Java 中使用正则表达式时,反斜杠 \ 需要使用双反斜杠 \ 转义。因此,在正则表达式中出现的 \w 需要写成 \w。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值