正则是专门针对字符串的,有以下功能
1:匹配 :实际上使用的是String的 boolean matches(String regex)方法
2:切割: 实际上使用的是String的 String[] split(String regex)方法
3:替换: 实际上使用的是String replaceAll(String regex, String replacement) 把字符串中符合正则的字符串替换为第二参数接收的字符串
4:获取: 从一个字符串中得到我们需要的内容
import java.util.*;
import java.util.regex.*;
class Demo7
{
public static void main(String[] args)
{
//match();
//splits();
//tiHuan();
huoQu();
}
//4:获取
public static void huoQu()
{
String ss = "zhu yi le,ming tian fang jia";//获取到由4个字母构成的单词
//定义获取的内容符合的正则表达式
String regex="[a-z]{4}";
//把正则表达式编译成Pattern类型的对象
Pattern pattern = Pattern.compile(regex);
//Pattern本身不具备从字符串获取内容的功能,所以需要使用Pattern对象得到Matcher对象
//Matcher对象具备获取的功能
Matcher matcher = pattern.matcher(ss);
//使用Matcher的方法来获取内容
//boolean boo = matcher.find();//先让Matcher对象去找,如果找到了返回true
//if(boo)
//System.out.println(matcher.group());//再得到Matcher对象找到的内容
while(matcher.find())
{
System.out.println(matcher.group());
}
}
//3:替换
public static void tiHuan()
{
String str1="zhangsan&&&&&&lisi*****wangwu######zhaoliu%%%%%%liuneng";
String ss = str1.replaceAll("(.)\\1+","$1");// $1表示取第一组的值
System.out.println(ss);
String str2="zhangsan293743423434lisi5675756767567676wangwu982345678zhaoliu2345liuneng";
String ss2 = str2.replaceAll("\\d{6,}","*******");
System.out.println(ss2);
String str3="13838384381";
String ss3 = str3.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
System.out.println(ss3);
}
//2:切割
public static void splits()
{
//String str1="zhangsan.lisi.wangwu.zhaoliu.liuneng";
//String regex="\\.";
//String str1="zhangsan lisi wangwu zhaoliu liuneng";
//String regex=" +";
String str1="zhangsan&&&&&&lisi*****wangwu######zhaoliu%%%%%%liuneng";
//括号中的点表示任意字符,后面的\\1表示取第一个括号匹配的内容,后面的加号表示匹配1次或1次以上
//二者加在一起就是某个字符重复两次或两次以上
String regex="(.)\\1+"; //分组
String[] arr = str1.split(regex);
for(String ss:arr)
{
System.out.println(ss);
}
}
//1:匹配
public static void match()
{
//验证手机号是否合法
String phone="13838384381";
String regex="1[345789]\\d{9}";
System.out.println(phone.matches(regex));
}
}
总结