菜鸡的Java笔记 - java 正则表达式
阅读原文时间:2022年03月10日阅读:1

正则表达式 RegularExpression
        了解正则表达式的好处
        正则表达式的基础语法
        正则表达式的具体操作
        
    content (内容)
        什么事正则表达式
            为了能够更加清楚的认识到正则的意义所在,下面编写一个简单的程序:判断某一个字符是否由数字组成
            
            范例:最原始实现

package cn.mysterious.study3;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "235481";  
    System.out.println(isNumber(str));  
}  
public static boolean isNumber(String data){

    char\[\] result = data.toCharArray(); // 变为字符数组  
    for (int i = 0; i < result.length; i++) {  
        if (result\[i\] < '0' || result\[i\] > '9') {  
            return false;  
        }  
    }  
    return true;  
}

}

但是以上的程序做法是可以完全简化的

package cn.mysterious.study3;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "235481";  
    System.out.println(str.matches("\\\\d+"));  
}

}

通过以上的代码就可以发现,正则表达式给我们用户带来最只管的感受是减少了程序的代码,实质上就属于加强了 String 的操作支持

        认识正则表达式(背)
            正则表达式是在 JDK.14 的时候正式追加到 java 之中的,其最早起源于 Linux 系统下
            最早的java开发时代如果要想使用正则开发,那么必须区通过 apache 下载相应的正则表达式的开发包才可以完成
            因为在 JDK1.4 中提供有一个新的程序包: java.util.regex ,就是正则的支持包,而且这个包中主要有两个类: Pattern, Matcher 类
            其中 Pattern 类中提供有常用正则标记说明,下面来看几个常用的正则语法:(两个 \\ 表示一个 \)
                1.字符( Characters 如果不加如量词,那么就表示单个字符)
                    a :表示由指定的字母 a 所组成
                    \\ :匹配“\”转义字符
                    \t :匹配“\t”转义字符
                    \n :匹配换行的转移字符
                
                2.字符范围(如果不加如量词,那么就表示单个字符)
                    [abc] :表示可能是字母 a,b,c 的任意一位
                    [^abc] :表示不是字母 a,b,c 的任意一位
                    [a-zA-Z] :表示由任意一位字母(小写或大写)组成
                    [0-9] :表示任意一位数字所组成
                
                3.简化表达式(如果不加如量词,那么就表示单个字符)
                    . :表示任意的一位字符
                    \d :表示任意的一位数字,等价于“ [0-9] ”;
                    \D :表示任意的一位非数字,等价于“ [^0-9] ”;
                    \w :表示任意的一位字符,有字母,数字,_ 所组成,等价于“ [a-zA-Z0-9_] ”;
                    \W :表示任意的一位非指定字符(不是字符,有字母,数字,_ 所组成),等价于“ [^a-zA-Z0-9_] ”;
                    \s :表示任意的一位空格,可能是: \n, \t;
                    \S :表示任意的一位非空格
                    
                4.边界匹配 (java 不要用)
                    ^ :表示正则匹配的开始
                    $ :表示正则匹配的结束
                    
                5.量词描述,如果没有量词,那么每一个出现的正则度只能够匹配一个字符
                    表达式? :表示此正则表达式可以出现0次或1次
                    表达式+ :表示此正则表达式可以出现1次或多次
                    表达式* :表示正则表达式可以出现0次,1次或多次
                    表达式{n}:表示正则表达式正好出现n次
                    表达式{n,}:表示正则表达式正好出现n次以上,包含n次
                    表达式{n,m}:表示正则表达式正好出现n~m次
                    
                6.逻辑运算
                    X正则Y正则:表示X正则之后紧跟着验证Y正则
                    X正则|Y正则:表示两个正则选一个
                    ():一组正则
                    
        String 对正则的支持 (离散数学)
            如果要进行正则的操作本质上应该使用 Pattern 或 Matcher 两个类完成,但是从实际的开发来讲,大部分的开发者不会去直接使用这两个类
            因为在JDK1.4之后, String 类对正则作出了支持,增加如下的诺干方法:

NO

方法名称

类型

类型

1

public boolean matches(String regex)

普通

正则匹配验证

2

public String replaceAll(String regex,String replacement)

普通

全部替换

3

public String replaceFirst(String regex,String replacement)

普通

替换首个

4

public String[] split(String regex)

普通

拆分

5

public String[] split(String regex,int limit)

普通

部分拆分

范例:进行替换

package cn.mysterious.study3;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "sdas6da6wdsdawd@#$5%sdawds456564dawdwww235481";  
    String regex = "\[^a-zA-Z\]";  
    System.out.println(str.replaceAll(regex, " "));  
}

}

范例:进行拆分

package cn.mysterious.study3;

import java.util.Arrays;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "sd3a5sd65a4s6d54a6s5d5asd546as4d6as5d55555ssssssss";  
    String regex = "\\\\d+";  // "\[0-9\]+"  
    System.out.println(Arrays.toString(str.split(regex)));  
}

}

对于替换与拆分操作使用正则并不麻烦,最麻烦的是进行字符串的结构验证
            
            范例:判断某一个字符穿是否是小数,如果是则将其转换为 Double 类型

package cn.mysterious.study3;

import java.util.Arrays;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "10.2";  
    String regex = "\\\\d+(\\\\.\\\\d+)?";  
    if (str.matches(regex)) {  
        System.out.println(Double.parseDouble(str));  
    }else {  
        System.out.println("匹配出错!");  
    }

}

}

范例:匹配日期
                如果要想将字符串变为日期则一定使用 SimpleDateFormat 程序类,但是这个类需要满足特定的结构要求

package cn.mysterious.study3;

import java.text.SimpleDateFormat;
import java.util.Arrays;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "2019-10-10";  
    String regex = "\\\\d{4}-\\\\d{2}-\\\\d{}";  
    if (str.matches(regex)) {  
        System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(str));  
    }else {  
        System.out.println("匹配出错!");  
    }

}

}

范例:匹配电话号码。而这个电话号码的组成可能有如下几种:
                1.4734644    \\d{7,8}
                2.010-4734644 或 0104734644        (\\d{3,4}-?)\\d{7,8}
                3.(010)-4734644    ((\\d{3,4}-?)|(\\(\\d{3,4}\\)-?))\\d{7,8}

package cn.mysterious.study3;

import java.text.SimpleDateFormat;
import java.util.Arrays;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "(010)-4734644";  
    String regex = "((\\\\d{3,4}-?)|(\\\\(\\\\d{3,4}\\\\)-?))\\\\d{7,8}";  
    System.out.println(str.matches(regex));

}

}

正则验证 email 地址那是相当好用的
            
            范例:验证 email 地址
                简单验证:email 有字母,数字,_ 所组成

package cn.mysterious.study3;

import java.text.SimpleDateFormat;
import java.util.Arrays;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "abc@a.c";  
    String regex = "\\\\w+@\\\\w+\\\\.\\\\w+";  
    System.out.println(str.matches(regex));

}

}

完整验证:在 email 中的用户名可以由字母,数字,_ , - ,. 所组成,长度6~30位,其中要求以字母开头
                同时在域名的后缀只能够是: .com, .cn, .com.cn, .net, .net.cn, .gov, .edu, .org, .me, .e

package cn.mysterious.study3;

import java.text.SimpleDateFormat;
import java.util.Arrays;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "kid\_187124304@feel.com";  
    String regex = "\[a-zA-Z\]\[a-zA-Z0-9\_\\\\-\\\\.\]{5,29}"  
        +"@\[a-zA-Z0-9\_\\\\-\\\\.\]+\\\\."  
        +"(com|cn|com\\\\.cn|net|net\\\\.cn|gov|edu|org|me|e)";  
    System.out.println(str.matches(regex));

}

}

对于这些正则都是属于常见操作,应该要熟练掌握
                
        java.util.regex 包中的直接操作
            实际上 String类中给出的一系列的操作,在 Pattern 和 Mathcher 类中都有支持
            
            1. Pattern 类;
                编译正则: public static Pattern compile(String regex)
                字符串拆分: public String[] split(CharSequence input)

package cn.mysterious.study3;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.regex.Pattern;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "kid\_187124304@feel.com";  
    String regex = "\[^a-zA-Z\]+";  
    Pattern pat = Pattern.compile(regex);// 编译正则  
    System.out.println(Arrays.toString(pat.split(str)));

}

}

2. Matcher 类主要是进行匹配
                    Matcher 类必须依靠 Pattern 类取得实例化对象: public Matcher matcher(CharSequence input)
                    在 Matcher 类中有如下方法:
                        字符串匹配: public boolean matches()
                        字符串替换: public String replaceAll(String replacement)
                        
                    范例:匹配操作

package cn.mysterious.study3;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression {

public static void main(String\[\] args) {  
    // TODO Auto-generated method stub  
    String str = "10010";  
    String regex = "\\\\d+";  
    Pattern pat = Pattern.compile(regex);// 编译正则  
    Matcher mat = pat.matcher(str);  
    System.out.println(mat.matches());

}

}

这两个类的主要功能都在 String 中提供了支持,所以大部分情况下不会考虑使用这两个类

    总结
        正则表达式提供了更为强大的字符串验证与操作的功能,对于正则操作常用标记必须记熟练
        虽然调用形式不同但是标准的正则支持是完全一样的