Fork me on GitHub

java正则表达式

String类三个和正则表达式相关的方法

public boolean matches(String regex) //判断字符串是否匹配给定的规则

举例:校验qq号码.
    1: 要求必须是5-15位数字
    2: 0不能开头
代码演示:
    String qq = "604154942";
    String regex = "[1-9][0-9]{4,14}";
    boolean flag2 = qq.matches(regex);

举例:校验手机号码
    1:要求为11位数字
2:第1位为1,第2位为3、4、5、7、8中的一个,后面9位为0到9之间的任意数字。
代码演示:
    String phone = "18800022116";
    String regex = "1[34578][0-9]{9}";
    boolean flag = phone.matches(regex);

public String[] split(String regex) //根据给定正则表达式的匹配规则,拆分此字符串

举例:分割出字符串中的的数字
代码演示:
String s = "18-22-40-65";
    String regex = "-";
    String[] result = s.split(regex);
代码演示:
    String s = "18 22 40 65";
    String regex = " ";
    String[] result = s.split(regex);

public String replaceAll(String regex,String replacement)  //将符合规则的字符串内容,全部替换为新字符串

举例:把文字中的数字替换成*
代码演示:
    String s = "Hello12345World6789012";
    String regex = "[0-9]";
    String result = s.replaceAll(regex, "*");

查找符合正则表达式的字符

Pattern编译正则表达式,Matcher类为封装结果

        String  str="匹配小数2.1,整数33,以及字母和数字的组合fsd535,但是.也可以匹配9点8,因为.代表任意字符?";
        String s = "\\d+.\\d+|\\w+";    //.代表任意字符,匹配项为  数字[1,]任意字符[1]数字[1,]或者字母和数字的组合[1,]
        Pattern  pattern= Pattern.compile(s);
        Matcher ma=pattern.matcher(str);

        while(ma.find()){
            System.out.println(ma.group());
        }

输出

小数正则表达式

([1-9]\d*\.?\d*)|(0\.\d*[1-9])

邮箱 

[a-zA-Z_0-9]+@[a-zA-Z_0-9]+(\\.[a-zA-Z_0-9]+)+

\\w+@\\w+(\\.\\w+)+

中文

[\u4e00-\u9fa5]+


posted @ 2018-06-27 11:57  秋夜雨巷  阅读(280)  评论(0编辑  收藏  举报