1.匹配驗證-驗證Email是否正確
public static void main(String[] args) {// 要驗證的字符串String str = "service@xsoftlab.net";// 郵箱驗證規則String regEx = "[a-zA-Z_]{1,}[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);
}
2.在字符串中查詢字符或者字符串
public static void main(String[] args) {// 要驗證的字符串String str = "baike.xsoftlab.net";// 正則表達式規則String regEx = "baike.*";// 編譯正則表達式Pattern pattern = Pattern.compile(regEx);// 忽略大小寫的寫法// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(str);// 查找字符串中是否有匹配正則表達式的字符/字符串boolean rs = matcher.find();System.out.println(rs);
}