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

来源:互联网 发布:java 树遍历treenode 编辑:程序博客网 时间:2024/06/08 19:41
  • 正则替换
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));    }}   */

这里写图片描述


℃江

0 0
原创粉丝点击