正则表达式Pattern

阅读更多

正则表达式是符合一定规则的表达式,用来专门操作字符串,对字符创进行匹配,切割,替换,获取。

 

例如,我们需要对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);
}
}

 

public static void homework2() {
		String str = "my dat1a";
		String str2 = "";
		String regex = "";
		String s1 = str.replaceAll(regex, "");
		System.out.println(s1);

		String regex2 = "(]]>)?( 
  

 

你可能感兴趣的:(正则表达式Pattern)