ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

day16正则表达式&枚举类

2022-01-23 20:58:50  阅读:157  来源: 互联网

标签:regex 匹配 String 正则表达式 枚举 System day16 println out


正则表达式的概述

正则表达式的概念:使用单个字符串来描述或者匹配一系列符合某种语法规则的字符串

1、通过大量的字符串寻找规律,得出定义规则

2、使用这种规则去匹配新的字符串

3、匹配成功做出相应的操作

正则表达式的基本语法

1、原义字符

字符本身就是一个正则

public class RedularDemo2 {
    public static void main(String[] args) {
        String str = "ab123342asdasqwe&;123.";
        //String类中有一个方法是替换功能,替换所有符合规则的字符
        //public String replaceAll(String regex,String replacement)
        // 用给定的替换替换与给定的regular expression匹配的此字符串的每个子字符串。
        String regex = "\\.";
        System.out.println(str.replaceAll(regex,"_"));//ab123342asdasqwe&;123_

        regex = "b";
        System.out.println(str.replaceAll(regex,"_"));//a_123342asdasqwe&;123.
    }
}

2、元字符

字符描述
\将下一个字符标记为一个特殊字符、或一个原义字符、或一个 向后引用、或一个八进制转义符。例如,'n' 匹配字符 "n"。'\n' 匹配一个换行符。序列 '\' 匹配 "" 而 "(" 则匹配 "("。
^匹配输入字符串的开始位置。如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配 '\n' 或 '\r' 之后的位置。
$匹配输入字符串的结束位置。如果设置了RegExp 对象的 Multiline 属性,$ 也匹配 '\n' 或 '\r' 之前的位置。
*匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。
+匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。
?匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 。? 等价于 {0,1}。
{n}n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。
{n,}n 是一个非负整数。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。
{n,m}m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。
?当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串 "oooo",'o+?' 将匹配单个 "o",而 'o+' 将匹配所有 'o'。
.匹配除换行符(\n、\r)之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用像"(.|\n)"的模式。
(pattern)匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中则使用 $0…$9 属性。要匹配圆括号字符,请使用 '(' 或 ')'。
(?:pattern)匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用 "或" 字符 (|) 来组合一个模式的各个部分是很有用。例如, 'industr(?:y|ies) 就是一个比 'industry|industries' 更简略的表达式。
(?=pattern)正向肯定预查(look ahead positive assert),在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,"Windows(?=95|98|NT|2000)"能匹配"Windows2000"中的"Windows",但不能匹配"Windows3.1"中的"Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。
(?!pattern)正向否定预查(negative assert),在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如"Windows(?!95|98|NT|2000)"能匹配"Windows3.1"中的"Windows",但不能匹配"Windows2000"中的"Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。
(?<=pattern)反向(look behind)肯定预查,与正向肯定预查类似,只是方向相反。例如,"(?<=95|98|NT|2000)Windows"能匹配"2000Windows"中的"Windows",但不能匹配"3.1Windows"中的"Windows"。
(?<!pattern)反向否定预查,与正向否定预查类似,只是方向相反。例如"(?<!95|98|NT|2000)Windows"能匹配"3.1Windows"中的"Windows",但不能匹配"2000Windows"中的"Windows"。
x|y匹配 x 或 y。例如,'z|food' 能匹配 "z" 或 "food"。'(z|f)ood' 则匹配 "zood" 或 "food"。
[xyz]字符集合。匹配所包含的任意一个字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'。
[^xyz]负值字符集合。匹配未包含的任意字符。例如, 'abc' 可以匹配 "plain" 中的'p'、'l'、'i'、'n'。
[a-z]字符范围。匹配指定范围内的任意字符。例如,'[a-z]' 可以匹配 'a' 到 'z' 范围内的任意小写字母字符。
[^a-z]负值字符范围。匹配任何不在指定范围内的任意字符。例如,'a-z' 可以匹配任何不在 'a' 到 'z' 范围内的任意字符。
\b匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B匹配非单词边界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\cx匹配由 x 指明的控制字符。例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。
\d匹配一个数字字符。等价于 [0-9]。
\D匹配一个非数字字符。等价于 0-9。
\f匹配一个换页符。等价于 \x0c 和 \cL。
\n匹配一个换行符。等价于 \x0a 和 \cJ。
\r匹配一个回车符。等价于 \x0d 和 \cM。
\s匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
\S匹配任何非空白字符。等价于 \f\n\r\t\v。
\t匹配一个制表符。等价于 \x09 和 \cI。
\v匹配一个垂直制表符。等价于 \x0b 和 \cK。
\w匹配字母、数字、下划线。等价于'[A-Za-z0-9_]'。
\W匹配非字母、数字、下划线。等价于 'A-Za-z0-9_'。
\xn匹配 n,其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如,'\x41' 匹配 "A"。'\x041' 则等价于 '\x04' & "1"。正则表达式中可以使用 ASCII 编码。
\num匹配 num,其中 num 是一个正整数。对所获取的匹配的引用。例如,'(.)\1' 匹配两个连续的相同字符。
\n标识一个八进制转义值或一个向后引用。如果 \n 之前至少 n 个获取的子表达式,则 n 为向后引用。否则,如果 n 为八进制数字 (0-7),则 n 为一个八进制转义值。
\nm标识一个八进制转义值或一个向后引用。如果 \nm 之前至少有 nm 个获得子表达式,则 nm 为向后引用。如果 \nm 之前至少有 n 个获取,则 n 为一个后跟文字 m 的向后引用。如果前面的条件都不满足,若 n 和 m 均为八进制数字 (0-7),则 \nm 将匹配八进制转义值 nm。
\nml如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0-7),则匹配八进制转义值 nml。
\un匹配 n,其中 n 是一个用四个十六进制数字表示的 Unicode 字符。例如, \u00A9 匹配版权符号 (?)。

 

2.1 字符类

[]

public class RegularDemo3 {
    public static void main(String[] args) {
        String s = "ab123342asdasqwe&;123.";
        //表示格式:[]
        //[]表示的是将字符进行归类,可以匹配出现在中括号中的任意一个字符
        //只要被匹配的字符串中存在a,b,2中任何一个,都会被匹配到
        String regex = "[ab2]";
        System.out.println(s.replaceAll(regex,"_"));//__1_334__sd_sqwe&;1_3.

        //需求:除了ab2以外,都要被匹配替换
        //^出现中括号代表的意思是取反,对不是ab2的字符进行匹配
        regex = "[^ab2]";
        System.out.println(s.replaceAll(regex,"_"));//ab_2___2a__a_______2__
    }
}

2.2 范围类

其实就是在字符类的基础上增加了一个范围

public class RegularDemo4 {
    public static void main(String[] args) {
        String regex = "[ab]";
        String s = "abcdefghijklmnABCDTW1234DWFadqwr&;123=.";
        System.out.println("匹配之前:" + s);//匹配之前:abcdefghijklmnABCDTW1234DWFadqwr&;123=.
        System.out.println("=========================================");
        System.out.println(s.replaceAll(regex, "_"));//__cdefghijklmnABCDTW1234DWF_dqwr&;123=.

        //需求:匹配字符串中所有小写的字母
        //[a-z]表示的是匹配a到z中的任意一个小写字母
        regex = "[a-z]";
        System.out.println(s.replaceAll(regex, "_"));//______________ABCDTW1234DWF_____&;123=.

        //[A-Z]表示的是匹配A到Z中的任意一个大写字母
        regex = "[A-Z]";
        System.out.println(s.replaceAll(regex, "_"));//abcdefghijklmn______1234___adqwr&;123=.

        //匹配大小写
//        regex = "[a-zA-Z]";
        regex = "[A-z]";
        System.out.println(s.replaceAll(regex, "_"));//____________________1234________&;123=.

        //匹配数字
        regex = "[0-9]";
        System.out.println(s.replaceAll(regex, "_"));//abcdefghijklmnABCDTW____DWFadqwr&;___=.

        //匹配数字和大小写字母
        regex = "[0-z&.]";
        System.out.println(s.replaceAll(regex, "_"));//_______________________________________
    }
}

2.3 预定义类:

\d == [0-9]数字
\D == [^0-9]非数字
\s == [\r\n\f\r]空白字符
\S == [^\r\n\f\r]非空白字符
\w == [a-zA-Z0-9]
\W == [^a-zA-Z0-9]
. == 代表任意字符

public class RegularDemo5 {
    public static void main(String[] args) {
        String regex = "[0-9]";
        String s = "abcde fghijklmn ABCDTW12.....34D WFadq r&;1!!!!23=.";
        System.out.println("匹配之前:" + s);//匹配之前:abcde fghijklmn ABCDTW12.....34D WFadq r&;1!!!!23=.
        System.out.println("=========================================");
        System.out.println(s.replaceAll(regex, "_"));//abcde fghijklmn ABCDTW__.....__D WFadq r&;_!!!!__=.

        regex = "\\d"; //[0-9]数字
        System.out.println(s.replaceAll(regex, "_"));//abcde fghijklmn ABCDTW__.....__D WFadq r&;_!!!!__=.

        regex = "\\D"; //表示匹配所有非数字的字符
        System.out.println(s.replaceAll(regex, "_"));//______________________12_____34___________1____23__

        regex = "\\s"; //匹配所有的空白字符
        System.out.println(s.replaceAll(regex, "_"));//abcde_fghijklmn_ABCDTW12.....34D_WFadq_r&;1!!!!23=.

        regex = "\\S"; //匹配所有的除空白字符以外的
        System.out.println(s.replaceAll(regex, "_"));//_____ _________ ________________ _____ ____________

        regex = "\\w"; //匹配所有的大小写字母和数字
        System.out.println(s.replaceAll(regex, "_"));//_____ _________ ________.....___ _____ _&;_!!!!__=.

        regex = "\\W"; //匹配所有的非大小写字母和数字
        System.out.println(s.replaceAll(regex, "_"));//abcde_fghijklmn_ABCDTW12_____34D_WFadq_r__1____23__

        regex = "."; // 表示的是匹配任意字符
        System.out.println(s.replaceAll(regex, "_"));//___________________________________________________

        regex = "\\."; //匹配.这个字符
        System.out.println(s.replaceAll(regex, "_"));//abcde fghijklmn ABCDTW12_____34D WFadq r&;1!!!!23=_

    }
}

2.4 边界类字符

^: 不在中括号中出现,表示的是以xxx开头
$: 以xxx结尾
\b: 单词边界
\B: 非单词边界

public class RegularDemo6 {
    public static void main(String[] args) {
        //在没有中括号的时候使用^,^表示的是以xxx开头,这里表示的是以ac开头
        String regex = "^abc";
        String s = "abcdefg";
        System.out.println("匹配之前:" + s);//匹配之前:abcdefg
        System.out.println("=========================================");
        System.out.println(s.replaceAll(regex, "_"));//_defg

        regex = "fg$";
        System.out.println(s.replaceAll(regex, "_"));//abcde_


        regex = "\\b";
        s = "hello worpd 888 1 2 & ; 0 a b c d";
        System.out.println("匹配之前:" + s);//匹配之前:hello worpd 888 1 2 & ; 0 a b c d
        System.out.println("===========================================");
        System.out.println(s.replaceAll(regex, "_"));//_hello_ _worpd_ _888_ _1_ _2_ & ; _0_ _a_ _b_ _c_ _d_

        regex = "\\B";
        System.out.println(s.replaceAll(regex, "_"));//h_e_l_l_o w_o_r_p_d 8_8_8 1 2 _&_ _;_ 0 a b c d

    }
}

2.5 量词

? : 出现了0次或者1次

+:出现了1次或者多次

*:出现了任意次

{n}:出现了正好n次

{n,m}:出现了n-m次

{n, };表示出现了至少n次

public class RegularDemo7 {
    public static void main(String[] args) {
        //匹配以a开头的0次或者1次
        String regex = "^a?";
        String s = "baaabcdefaaaaaag";
        System.out.println("匹配之前:" + s);//匹配之前:baaabcdefaaaaaag
        System.out.println("=======================================");
        System.out.println(s.replaceAll(regex, "_"));//_baaabcdefaaaaaag

        regex = "^a+";
        System.out.println(s.replaceAll(regex, "_"));//baaabcdefaaaaaag

        regex = "^a*";
        System.out.println(s.replaceAll(regex, "_"));//_baaabcdefaaaaaag

        //{n}:出现了正好n次
        //需求:匹配一个字符串a字符连续出现了6
        regex = "a{6}"; // aaaaaa
        System.out.println(s.replaceAll(regex, "*"));//baaabcdef*g

        //{n,m}:出现了n-m次
        regex = "a{3,4}"; // 匹配的是a连续出现的次数在3-4之间
        //范围量词优先按多次匹配
        System.out.println(s.replaceAll(regex, "*"));//b*bcdef*aag

        //{n, };表示出现了至少n次
        regex = "a{6,}";
        System.out.println(s.replaceAll(regex, "*"));//baaabcdef*g
    }
}

2.6 分组:()

public class RegularDemo8 {
    public static void main(String[] args) {
        //它表示匹配的内容是ab加上1-2个c
        String reagex = "abc{1,2}";
        String s = "abcccccABC123123ABCabcccccABC123123ABCabcccccABC123123ABCabcabcabc123";
        System.out.println("匹配之前:" + s);//匹配之前abcccccABC123123ABCabcccccABC123123ABCabcccccABC123123ABCabcabcabc123
        System.out.println("===========================================================");
        System.out.println(s.replaceAll(reagex, "_"));//_cccABC123123ABC_cccABC123123ABC_cccABC123123ABC___123

        //加上小括号表示分组
        //表示abc整体出现了1-2次
        reagex = "(abc){1,2}";
        System.out.println(s.replaceAll(reagex, "_"));//_ccccABC123123ABC_ccccABC123123ABC_ccccABC123123ABC__123

        reagex = "ABC(abc){1,}";   //ABCabcabc
        System.out.println(s.replaceAll(reagex, "_"));//abcccccABC123123_ccccABC123123_ccccABC123123_123

        //matches
        System.out.println(s.matches(reagex));//false
    }

}

2.7 反向引用(用来取值的)

$: 取值,取对应分组号中的值,每一个分组的编号从1开始

需求:2022-01-23 ---> 01/23/2022

public class RegularDemo9 {
    public static void main(String[] args) {
        //2022-01-23
        String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
        String s = "2022-01-23  2022-02-24";
        System.out.println(s.replaceAll(regex,"$2/$3/$1"));//01/23/2022  02/24/2022

        //分组中如果我不想让它生成编号 ?:
        regex = "(\\d{4})-(?:\\d{2})-(\\d{2})";
        System.out.println(s.replaceAll(regex,"$2/$1"));//23/2022  24/2022
    }
}

3、正则表达式在java中的应用

在java中是如何让使用正则表达式来实现相关操作的?

1、字符串的查找操作:Pattern和Matcher

2、字符串的匹配操作:可以使用该字符串的matches方法

3、字符串的替换操作:字符串String类中有replaceAll()方法和replaceFirst()方法

4、字符串的分割工作:字符串String类中有split()方法

package com.shujia.wyh.day16;

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

public class RegularDemo10 {
    public static void main(String[] args) {
        String regex = "\\w{3,}";
        String s = "abcd123";
        System.out.println(s.matches(regex));//true

        regex = "[a-z]{2,}";
        s = "abc defg hello111";
        System.out.println(s.replaceAll(regex, "_"));//_ _ _111
        System.out.println(s.replaceFirst(regex, "_"));//_ defg hello111

        s = "abc sbdf 123ab sa123bddss &";
        String[] s1 = s.split(" ");
        //工具类遍历数组
        System.out.println(Arrays.toString(s1));//[abc, sbdf, 123ab, sa123bddss, &]

        s = "abc sbdf 123ab sa123bddss &";
        String[] s2 = s.split("a");
        //工具类遍历数组
        System.out.println(Arrays.toString(s2));//[, bc sbdf 123, b s, 123bddss &]

        //Pattern和Matcher
        regex = "\\w{3,7}";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher("abcd123");
        System.out.println(matcher.matches());//true
    }
}

例:将字符串“我我我我我我我..........我.......要要要要要..................要要要要...学习习习习.......习习习习习习习习编程程程程程程.......程程程程程程程程程”变成“我要学习编程”

public class RegularDemo11 {
    public static void main(String[] args) {
        String s = "我我我我我我我..........我.......要要要要要..................要要要要...学习习习习.......习习习习习习习习编程程程程程程.......程程程程程程程程程";
        //1、先将.去掉
        String regex = "\\.+";
        String s1 = s.replaceAll(regex, "");
        System.out.println(s1);

        //2、合并叠词
        regex = "(.)\\1+";//反向引用取$1  
        String s2 = s1.replaceAll(regex, "$1");
        System.out.println(s2);

    }
}

枚举类型

1、当一个类的对象只有有限个的时候,确定的,我们就可以把这个类定义为枚举类

2、当需要定义一组常量的时候,强烈建议使用枚举

如何定义一个枚举类?

根据JDK的版本不同,实现的方式不同

1、在JDK1.5之前,自定义一个枚举类

1、需要将构造方法私有化,保证类的对象的个数是有限个的

2、创建成员变量,必须把它定义为常量

3、提供公共的静态的成员变量给外界获取枚举类的对象

4、只提供公共的get方法

5、重写toString()方法

public class EnumDemo1 {
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);
        System.out.println(spring.getSEASON_NAME());
        System.out.println(spring.getSEASON_DESC());

    }
}

class Season{
    //2、创建Seanson的成员变量,必须把它定义为常量
    private final String SEASON_NAME;
    private final String SEASON_DESC;


    //1、需要将构造方法私有化,保证类的对象的个数是有限个的
    private Season(String SEASON_NAME,String SEASON_DESC){
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }

    //3、提供公共的静态的成员变量给外界获取枚举类的对象
    public static final Season SPRING = new Season("春天","春暖花开");
    public static final Season SUMMER = new Season("夏天","烈日炎炎");
    public static final Season AUTUMN = new Season("秋天","秋高气爽");
    public static final Season WINTER = new Season("冬天","白雪皑皑");

    //4、只提供公共的get方法
    public String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }

    //5、重写toString()方法
    @Override
    public String toString() {
        return "Season{" +
                "SEASON_NAME='" + SEASON_NAME + '\'' +
                ", SEASON_DESC='" + SEASON_DESC + '\'' +
                '}';
    }
}

2、在JDK1.5之后,通过java提供了一个叫做enum的关键字创建枚举类

1、需要将构造方法私有化,保证类的对象的个数是有限个的

2、创建成员变量,必须把它定义为常量

3、枚举有的有限个对象,对象之间通过逗号连接,最后一个分号结尾。枚举相关的放在头部

4、只提供公共的get方法

public class EnumDemo2 {
    public static void main(String[] args) {
        Season2 spring = Season2.SPRING;
        System.out.println(spring);
        System.out.println(Season2.class.getSuperclass());//枚举都有父类Enum
    }
}

enum Season2{

    //3、枚举有的有限个对象,对象之间通过逗号连接,最后一个分号结尾
    //枚举相关的放在头部
    SPRING("春天", "万物复苏"),
    SUMMER("夏天", "烈日炎炎"),
    AUTUMN("秋天", "秋高气爽"),
    WINTER("冬天", "白雪皑皑");

    //2、创建Season2的属性,常量处理
    private final String SEASON_NAME;
    private final String SEASON_DESC;


    //1、要保证类的对象的个数是有限的
    //那么我们必须要私有构造方法
    private Season2(String SEASON_NAME,String SEASON_DESC){
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }


    //4、提供SEASON_NAME和SEASON_DESC的get方法
    public String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }

}

枚举类可以实现接口

1、直接在枚举类实现接口中的抽象方法

2、在每个枚举对象中实现

标签:regex,匹配,String,正则表达式,枚举,System,day16,println,out
来源: https://blog.csdn.net/qnmdlzg/article/details/122656138

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有