正则表达式匹配邮箱
使用 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。