Java 正则初探

正则表达 初探*

走进沼泽

问题引出

  • 问题:判断一个String字符串是否为数字字符串
    • 将字符串转换为字符数组
    • 判断每一个字符是否在“0~9”范围之间
public class TestDemo {
    public static void main(String [] args) {
        String str = "123" ;
        System.out.println(isNumber(str));
    }
    public static boolean isNumber(String temp) {
        char data [] = temp.toCharArray();
        for (int x = 0 ; x < data.length ; x ++ ) {
            if (data[x] > '9' || data[x] < '0') {
                return false ;
            }
        }
        return true;
    }
}
  • 上述问题改用正则表达判断
public class TestDemo {
    public static void main(String [] args) {
        String str = "123" ;
        System.out.println(str.matches("\\d+"));
    }
}

java.util.regex 包

Pattern 类

  • 需要使用 compile() 方法来取得类对象

Matcher 类

  • 需要 Pattern 类取得

正则标记(熟记)

java.util.regex.Pattern 中定义正则标记

字符 匹配
x 字符 x
 \ 反斜杠
 t 制表符
 n 换行
  • ps在正则中出现对符号的正则,均需要反斜杠进行转移( )
字符集 匹配
[abc] 表示字符a,b,c中任意一位
[^abc] 表示不是字符 a,b,c 中任意的一位
[a-z] 所有的小写字母
[A-Z] 所有的大写字母
字符集表达式 匹配
. 任意一位的字符
\d 匹配一位数字“[0-9]"(在代码中两杠等于一个杠)
\D 不匹配数字 [ ^0-9 ]
\s 任意的空白字符 (\t \n ……)
\S 任意的非空白字符
\w 表示任意字母、数字、下划线 [ a-zA-Z_0-9]
\W 表示非字母、数字、下划线 [ ^a-zA-Z_0-9]
  • 边界匹配,建议在JavaScript中使用,不在java中使用
符号 匹配
^ 正则的开始
$ 正则的结束
  • 数量表达
    • 正则 ?:表示此正则可以出现0或1次
    • 正则 + :表示此正则可以出现1或多次
    • 正则 * :表示此正则可以出现0、1或多次
    • 正则 {n}:表示此正则出现N次
    • 正则{n,}:表示此正则出现N+次
    • 正则{n,m}: 表示此正则出现n~m次
  • 逻辑运算
    • 正则1 正则2:正则1判断以后继续完成判断正则2
    • 正则1|正则2:正则1或正则2 有一组满足即可
    • (正则集):将多个正则作为一组,可以设置这一组单独设置出现的次数

String 类对正则的支持

方法

  • public boolean matches(String regex)
    • 正则验证
  • public String replaceAll(String regex , String replacement)
    • 全部替换
  • public String replaceFirst (String regex , String replacement)
    • 替换首个
  • public String [] split(String regex)
    • 全部拆分
  • public String [] split(String regex , int limit)
    • 部分拆分

实例

  • 字符串替换
public class TestDemo {
    public static void main(String [] args) {
        String str = "Mirror is niubi" ;
        String regex = "[^a-z]" ; // 正则
        System.out.println(str.replaceAll(regex,""));
    }
}

将不是小写的字母用空字符代替

  • 分隔字符
public class TestDemo {
    public static void main(String [] args) {
        String str = "Mirror12342is1231niu123123bi" ;
        String regex = "\\d+" ; // 正则 1个以上的数字
        String result [] = str.split(regex); // 数组
        for (int x = 0; x < result.length; x++) {
            System.out.println(result[x]);
        }
    }
}

按照数字为条件分隔字符,并被分隔的字符串存入数组中

  • 验证字符串是否是数字,如果是变为double型
public class TestDemo {
    public static void main(String [] args) {
        String str = "10.1" ;
        String regex = "\\d+(\\.\\d+)?" ; // 正则  小数
        System.out.println(str.matches(regex));
        if (str.matches(regex)) {
            System.out.println(Double.parseDouble(str));
            // 将str转换为double输出
        }
    }
}
  • 判断str是否是IPv4地址
public class TestDemo {
    public static void main(String [] args) {
        String str = "192.168.1.1" ;
        String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" ; 
        String regexs = (\\d{1,3}\\.){3}\\d{1,3}; //正则简化 
        System.out.println(str.matches(regex));
        if (str.matches(regex)) {
            System.out.println(str);
        }
    }
}
  • 判断是否为日期格式,如果是转为Date型数据
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDemo {
    public static void main(String [] args) throws ParseException {
        String str = "2009-01-01" ;
        String regex = "\\d{4}-\\d{2}-\\d{2}" ; 
        System.out.println(str.matches(regex));
        if (str.matches(regex)) {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
            System.out.println(date);
        }
    }
}
  • 判断电话号码:(如下是合法的电话号码格式)

    12345678

    010-12345678

    (010)-12345678

public class TestDemo {
    public static void main(String [] args) throws ParseException {
        String str = "(010)-12345678" ;
//      String regex = "(\\d{7,8})|(\\d{3,4}-\\d{7,8})|(\\(\\d{3,4}\\)-\\d{7,8})" ;
        String regex = "((\\d{3,4}-)|(\\(\\d{3,4}\\)-)?\\d{7,8})";
        System.out.println(str.matches(regex));
    }
}

最原始的 第4行 正则是繁琐的,而第5行 正则则是简单的,由于电话号码的前缀是特殊的三种状态:无前缀、有前缀、带括号的前缀;所以我们运用括号来将后两种的前缀状态进行判断,设置了"?" 符号表示正则只使用一次正则。

  • E-mail地址验证*

    地址由字母、数字、下划线组成

    [email protected](模拟的虚假mail)

    用户名要求由字母、数字、下划线、数字点组成,其中必须以字母开头、字母数字做结尾。用户名长度不超过30;而根域名只可以是指定的根域名

public class TestDemo {
    public static void main(String [] args) throws ParseException {
        String str = "[email protected]" ;
        String regex = "[a-zA-Z]?[a-zA-Z0-9_\\.]{0,28}[0-9a-zA-Z]\\@?\\w+\\.?(com|net|cn|gov|edu|org)";
        System.out.println(str.matches(regex));
    }
}

java.util.regex 包

Pattern

public class TestDemo {
    public static void main(String [] args) throws ParseException {
        String str = "[email protected]" ;
        String regex = "\\d+";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);// 编译正则
        String result [] = pattern.split(str); // 拆分字符串
        System.out.println(Arrays.toString(result)); //输出结果
        
    }

Matcher

public class TestDemo {
    public static void main(String [] args) throws ParseException {
        String str = "1234567" ;
        String regex = "\\d+";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);// 编译正则
        Matcher mat = pattern.matcher(str); // 进行正则匹配
        System.out.println(mat.matches()); // 匹配结果
    }
}

猜你喜欢

转载自www.cnblogs.com/wangyuyang1016/p/11129124.html
今日推荐