JAVA:正则表达式(代码说话)

  • 正则替换
package cn.dujiang.demo;
/**
 *正则替换,将大写字母替换成了空字符串,输出的就是小写字母咯
 * @author Dujiang
 *
 */
public class TestDemo {
    public static void main(String[] args) throws Exception {
        String str = "JHFUKFYLUIjsuadaJHKHi&*^$&($_)&:“《》?《";
        String regex = "[^a-z]";  //把不是小写字母的摘出来,放到一个人空的字符串中
        System.out.println(str.replaceAll(regex, ""));
    }
}

这里写图片描述


  • 正则字符串的拆分
package cn.dujiang.demo;
/**
 *以数字为分割线,把代码进行了拆分
 * @author Dujiang
 *
 */
public class TestDemo {
    public static void main(String[] args) throws Exception {
        String str = "145HHhh7645sa:“L[p;[jk45s2a3hy|";
        String regex = "\\d+";  //表示一位及一位以上数字的拆分
        String result[] = str.split(regex) ;
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
    }
}

这里写图片描述


  • 正则判断验证字符串
package cn.dujiang.demo;
/**
 *验证一个字符串是否是数字,如果是则将其变为double型
 *1.数字有可能整数也可能是小数
 * @author Dujiang
 *
 */
public class TestDemo {
    public static void main(String[] args) throws Exception {
       String str = "10.1" ;
       String regex = "\\d+(\\.\\d+)?" ;  //注意一定要把"."和点后的数字当成一个整体,这个整体要么出现一次,要么不出现
       System.out.println(str.matches(regex));
       if (str.matches(regex)) {//转型之前要进行验证
           System.out.println(Double.parseDouble(str));
       }
    }
}

这里写图片描述


  • 判定给定字符串的地址
package cn.dujiang.demo;
/**
 *判断给定的字符串是否是一个IP地址(IPV4)
 * @author Dujiang
 *
 */
public class TestDemo {
    public static void main(String[] args) throws Exception {
       String str = "192.0.1.1" ;
       String regex = "(\\d{1,3}\\.){3}\\d{1,3}" ;  
       System.out.println(str.matches(regex));

    }
}


/*package cn.dujiang.demo;

public class TestDemo {
    public static void main(String[] args) throws Exception {
       String str = "192.0.1.1" ;
       String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" ;  
       System.out.println(str.matches(regex));

    }
}   
*/

这里写图片描述


℃江

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值