正则表达式是符合一定规则的表达式,用来专门操作字符串,对字符创进行匹配,切割,替换,获取。
例如,我们需要对QQ号码格式进行检验
规则是长度6~12位 不能0开头 只能是数字,我们可以一位一位进行比较,利用parseLong进行判断,或者是用正则表达式来匹配[1-9][0-9]{4,14} 或者 [1-9]\d{4,14}
(a|b|ccc) a或者b或者ccc
检查IP
public static void checkIP(String ip) { String rex = "((\\d|\\d\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|\\d\\d|1\\d\\d|2[0-4]\\d|25[0-5])"; System.out.println(ip.matches(rex)); }
提取邮箱
public static void homework1() {
String str = "sassasa [email protected] cssafdsfs [email protected] sdsdsdsd";
String regex = "\\w+@(\\w{2,3}\\.)+\\w{2,3}";
String string[] = str.split(" ");
for (String s : string) {
if (s.matches(regex))
System.out.println(s);
}
}
String str = "sassasa [email protected] cssafdsfs [email protected] sdsdsdsd";
String regex = "\\w+@(\\w{2,3}\\.)+\\w{2,3}";
String string[] = str.split(" ");
for (String s : string) {
if (s.matches(regex))
System.out.println(s);
}
}
public static void homework2() { String str = "<user>my dat1a</user>"; String str2 = "<driver><![CDATA[oracle.jdbc.driver.OracleDriver]]></driver>"; String regex = "</?\\w*>"; String s1 = str.replaceAll(regex, ""); System.out.println(s1); String regex2 = "(]]>)?</?\\w*>(<!\\[CDATA\\[)?"; String s2 = str2.replaceAll(regex2, ""); System.out.println(s2); }