////匹配
使用的是String中的matches()方法
//////分割
使用的是String中的split()方法
///替换
使用的是String中的replaceAll()方法
- package com.xuan.demo;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class RegexDemo {
- public static void main(String[] args){
- System.out.println("正则表达式");
- ///匹配
- RegexFunction2();
- ///分割
- sqplitDemo();
- ///替换
- replaceAllDemo();
- //获取
- PatternDemo();
- }
- public static void PatternDemo() {
- String str="ni lov ming,xixi,haha I Love You, fan xiaoxiao,jia dashu";
- //String regex="[a-z]{3}";///这写法获取有问题,没有指定边界
- String regex="\\b[a-z]{3}\\b";//有指定边界
- //将正则封装成对象
- Pattern p=Pattern.compile(regex);
- //通过正则获取匹配对象
- Matcher m=p.matcher(str);
- //m.find();///查找,找到返回true
- while(m.find()){
- System.out.println("-----:"+m.group());
- }
- }
- ///替换
- public static void replaceAllDemo() {
- String str="xixitttttthahaniniwwwwwwwwwhehe";
- ///将叠词替换成#号
- //str=str.replaceAll("(.)\\1+", "#");//把连续重复的替换成#号
- str=str.replaceAll("(.)\\1+", "$1");//把连续重复的替换成一个:==>xixithahaniniwhehe
- System.out.println("======>"+str);
- String tel ="15800001111";
- ///(\\d{3})封装成组$1,(\\d{4})封装成组$2
- tel=tel.replaceAll("(\\d{3})\\d{5}(\\d{3})", "$1****$2");
- System.out.println("=====>"+tel);///===>158****111
- }
- ///分割
- public static void sqplitDemo() {
- String str="xiaoming wangcai xiaoqiang xiaoli";
- String[] names=str.split("\\ ");
- /*String str="xiaoming.wangcai.xiaoqiang";
- String[] names=str.split("\\.");*/
- for(String name : names){
- System.out.println("----->"+name);
- }
- }
- ///匹配
- public static void RegexFunction2() {
- ///手机校验
- String tel="15800001111";
- ///第一位只能为1,第二位:只能是3,5,8,;后面9位数只能是数字,不能出现字母
- //String regex="1[358][0-9]{9}";
- String regex="1[358]\\d{9}";//简写
- boolean b=tel.matches(regex);
- System.out.println(tel+"==>"+b);
- }
- }