学习Java中正则表达式-验证email邮箱
public static void main(String[] args) {
// 要验证的字符串
String str = "service@xsoftlab.net";
// 邮箱验证规则
String regEx = "[a-zA-Z_]{0,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
System.out.println(rs);
}
在字符串中找到符合规则的字符
public static void main(String[] args) {
// 要验证的字符串
String str = “这是一个正则表达式字符串查找的示例12345,正则表达式好厉害呀45678”;
// 正则表达式规则
String regEx = “\d+”;
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 查找字符串中是否有匹配正则表达式的字符/字符串
while (matcher.find()) {
System.out.println(matcher.group());
}
}