示例
String.split
public String[] split(String regex,int limit)
将此字符串拆分为给定的regular expression的匹配
String a = "as;df;gh";
String[] array = a.split(";");
System.out.println(Arrays.toString(array));
String.matches
public boolean matches(String regex)
告诉这个字符串是否匹配给定的regular expression
String p = "ab";
boolean b = p.matches("a");
System.out.println(b);
x|y匹配x或y
String p = "a";
boolean b = p.matches("(a|b)");
System.out.println(b);
\\d匹配一个数字
String p = "5";
boolean b = p.matches("\\d");
System.out.println(b);
\\d*匹配任意个数字
String p = "1008611";
boolean b = p.matches("\\d*");
System.out.println(b);
\\d{3,6}匹配3-6位数字
String p = "12345";
boolean b = p.matches("\\d{3,6}");
System.out.println(b);
/*
\\d{9}匹配9位数字
\\d{3,}匹配至少3位数字
*/
[3578]匹配3或5或7或8
String p = "8573";
boolean b = p.matches("[3578]*");
System.out.println(b);
[a-z]匹配小写字母 [A-Z]匹配大写字母
String p = "ASDfgh";
boolean b = p.matches("[A-z]*");
System.out.println(b);
\\w匹配大小写字母 数字 _
String p = "asdASD123_";
boolean b = p.matches("\\w*");
System.out.println(b);
/*
\\W匹配非大小写字母 数字 _
*/
实例
匹配QQ号
String p = "230089250";
boolean b = p.matches("\\d{9.11}");
System.out.println(b);
匹配手机号
String p = "13555555555";
boolean b = p.matches("1[3578]\\d{9}");
System.out.println(b);
匹配邮箱
String p = "230089250@qq.com";
boolean b = p.matches("\\w{6,10}@\\w{2,6}\\.(com|com\\.cn)");
System.out.println(b);
/*
"|","."为正则表达式中的符号,所以在使用时需要转义符\\
*/
字符串替换(String.replace)
replace (CharSequence target, CharSequence replacement)
将与字面目标序列匹配的字符串的每个子字符串替换为指定的字面替换序列
replaceAll(String regex, String replacement)
用给定的替换替换与给定的regular expression 匹配的此字符串的每个子字符串
replacerirst(String regex, String replacement)
用给定的替换替换与给定的 regular expression匹配的此字符串的第一个子字符串
String s = "a2cd3ef4g";
String s1 = s.replace("c", "C");
String s2 = s.replaceAll("\\d", "C");
String s3= s.replaceFirst("\\d","C");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);