Regular expressions and enumerations

Posted by eruiz1973 on Fri, 04 Feb 2022 05:35:12 +0100

1, Regular expression

1. Purpose

Regular expression is a technology independent of java and not attached to java, but it can be used in java, python/js, etc

Handle the complex search / replacement / matching / segmentation of strings through regular expressions

2. Overview

Use a single string to describe or match a series of strings that conform to certain syntax rules

3. Use steps

(1) Find the rules through a large number of strings and get the definition rules

(2) Use this rule to match new strings

(3) The matching is successful and the corresponding operation is made

4. Basic grammar

1. Original character: the character itself is a regular character

String str = "ab1&;3.";
        //public String replaceAll(String regex,String replacement)
        // Replace each substring of this string that matches the given regex with the given string.
        String regex = "\\."; 
        System.out.println(str.replaceAll(regex,"_"));//ab1&; 3_   Replaced

        regex = "b";
        System.out.println(str.replaceAll(regex,"_"));//a_ 1&; 3. Replaced b

2. Metacharacter

(1) Character class []

public class RegularDemo3 {
    public static void main(String[] args) {
        String s = "ab123342asdasqwe&;123.";
        //Presentation format: []
        //[] refers to the classification of characters, which can match any character appearing in brackets
        //As long as there is a string, it will be matched to any one of B
        String regex = "[ab2]";
        System.out.println(s.replaceAll(regex,"_"));

        //Requirements: all but ab2 should be matched and replaced
        //^The presence of square brackets means to reverse and match characters that are not ab2
        regex = "[^ab2]";
        System.out.println(s.replaceAll(regex,"_"));
    }
}
//Results__ 1_ 334__ sd_ sqwe&; 1_ three
         ab_2___2a__a_______2__

(2) Scope class

In fact, it adds a range based on the character class

public class RegularDemo4 {
    public static void main(String[] args) {
        String regex = "[ab]";
        String s = "abcdefghijklmnABCDTW1234DWFadqwr&;123=.";
        System.out.println("Before matching:" + s);
        System.out.println("=========================================");
        System.out.println(s.replaceAll(regex, "_"));

        //Requirement: matches all lowercase letters in the string
        //[a-z] means matching any lowercase letter from a to z
        regex = "[a-z]";
        System.out.println(s.replaceAll(regex, "_"));

        //[A-Z] indicates matching any capital letter from a to Z
        regex = "[A-Z]";
        System.out.println(s.replaceAll(regex, "_"));

        //Want to match both uppercase and lowercase?
//      regex = "[a-zA-Z]";   regex = "[A-z]";
        System.out.println(s.replaceAll(regex, "_"));

        //What if you want to match the numbers now?
        regex = "[0-9]";
        System.out.println(s.replaceAll(regex, "_"));

        //You want to match numbers and uppercase and lowercase letters
        regex = "[0-z&.]";
        System.out.println(s.replaceAll(regex, "_"));
    }
}
result
 Before matching: abcdefghijklmnABCDTW1234DWFadqwr&;123=.
=========================================
__cdefghijklmnABCDTW1234DWF_dqwr&;123=.
______________ABCDTW1234DWF_____&;123=.
abcdefghijklmn______1234___adqwr&;123=.
____________________1234________&;123=.
abcdefghijklmnABCDTW____DWFadqwr&;___=.
_______________________________________

(3) Predefined classes

According to the above range class, the corresponding can be interchanged

\d == [0-9]number
\D == [^0-9]Non numeric
\s == [\r\n\f\r]White space character
\S == [^\r\n\f\r]White space character
\w == [a-zA-Z0-9]
\W == [^a-zA-Z0-9]
The above is the time to add double\\,Example:\\d
. == Represents any character
\\.express.character

(4) Boundary class character

^: Does not appear in square brackets, indicating that xxx start
$: with xxx ending
 It's also double when used below\\
\b: Word boundary, this word is not that word, and a single letter is also a word
\B: Non word boundary
 String regex = "^abc";
        String s = "abcdefg";
        System.out.println("Before matching:" + s);
        System.out.println("=========================================");
        System.out.println(s.replaceAll(regex, "_"));

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


        regex = "\\b";
        s = "hello worpd 888 1 2 & ; 0 a b c d";
        System.out.println("Before matching:" + s);
        System.out.println("===========================================");
        System.out.println(s.replaceAll(regex, "_"));

        regex = "\\B";
        System.out.println(s.replaceAll(regex, "_"));
result:
Before matching: abcdefg
=========================================
_defg
abcde_
Before matching: hello worpd 888 1 2 & ; 0 a b c d
===========================================
_hello_ _worpd_ _888_ _1_ _2_ & ; _0_ _a_ _b_ _c_ _d_
h_e_l_l_o w_o_r_p_d 8_8_8 1 2 _&_ _;_ 0 a b c d

(5) Quantifier

? : 0 or 1 occurrences
+: One or more times
*: Any number of times
{n}:It happened n second
{n,m}: There it is n-m second
{n, };Indicates that at least n second
        //Match 0 or 1 times starting with a
        String regex = "^a?";
        String s = "baaabcdefaaaaaag";
        System.out.println("Before matching:" + s);
        System.out.println("=======================================");
        System.out.println(s.replaceAll(regex, "_"));

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

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

        //{n} : exactly n times
        //Requirement: match a string, a character appears for 6 consecutive times
        regex = "a{6}"; // aaaaaa
        System.out.println(s.replaceAll(regex, "*"));

        //{n,m}: n-m occurrences
        regex = "a{3,4}"; // The matching is that the number of consecutive occurrences of a is between 3-4
        System.out.println(s.replaceAll(regex, "*"));

        //{n, }; Indicates at least n occurrences
        regex = "a{6,}";
        System.out.println(s.replaceAll(regex, "*"));

        //Verify qq
        regex = "[1-9][0-9]{4,9}";
        s = "1165872335";
        System.out.println(s.replaceAll(regex, "Match successful"));
result
 Before matching: baaabcdefaaaaaag
=======================================
_baaabcdefaaaaaag
baaabcdefaaaaaag
_baaabcdefaaaaaag
baaabcdef*g
b*bcdef*aag
baaabcdef*g
 Match successful

(6) Group ()

String s = "abccccabc123abcabc123A";
//Parentheses indicate grouping
//Indicates that abc appears 1-2 times as a whole
reagex = "(abc){1,2}";
System.out.println(s.replaceAll(reagex, "_"));

result:_cc_123__123A

(7) Back reference (used to get value)

$: value, take the value in the corresponding group number, and the number of each group starts from 1

/*
        Requirement: 2022-01-23 -- > 01 / 23 / 2022 is completed by using the back reference in the regular
 */
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"));

        //In the group, if I don't want it to generate a number?:
        regex = "(\\d{4})-(?:\\d{2})-(\\d{2})";
//        System.out.println(s.replaceAll(regex,"$2/$3/$1"));
        System.out.println(s.replaceAll(regex,"$2/$1"));
    }
}
result;
01/23/2022  02/24/2022
23/2022  24/2022

2, Enumeration

1. Enumeration type

(1) When there are only a limited number of objects in a class, we can define this class as an enumeration class

give an example:

Monday Sunday

Gender: man (male), Woman (female)

Season: Spring Winter

(2) Enumeration is strongly recommended when you need to define a set of constants

Define an enumeration class: the implementation method is different according to the version of JDK

JDK1. Before 5: customize an enumeration class

Customize an enumeration class:
package com.shujia.wyh.day16;

/*
        Custom enumeration class with a season

 */
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. To create a member variable of Seanson, you must define it as a constant
    private final String SEASON_NAME;
    private final String SEASON_DESC;


    //1. The construction method needs to be privatized to ensure that the number of objects of the class is limited
    private Season(String SEASON_NAME,String SEASON_DESC){
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }

    //3. Provide public static member variables to the outside world to obtain the objects of enumeration classes
    public static final Season SPRING = new Season("spring","in the warm spring , flowers are coming out with a rush");
    public static final Season SUMMER = new Season("summer","Scorching sun");
    public static final Season AUTUMN = new Season("autumn","fresh autumn weather");
    public static final Season WINTER = new Season("winter","snow gleams white");

    //4. Only public get methods are provided
    public String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }

    //5. Override toString() method
    @Override
    public String toString() {
        return "Season{" +
                "SEASON_NAME='" + SEASON_NAME + '\'' +
                ", SEASON_DESC='" + SEASON_DESC + '\'' +
                '}';
    }
}

Output result:

Season{SEASON_NAME='spring', SEASON_DESC='in the warm spring , flowers are coming out with a rush'}
spring
 in the warm spring , flowers are coming out with a rush


JDK1. After 5: define the enumeration class through the keyword enum

public class EnumDemo2 {
    public static void main(String[] args) {
        Season2 spring = Season2.SPRING;
        System.out.println(spring);
        System.out.println(Season2.class.getSuperclass());
    }
}
​
/**
 *  Customize a season enumeration class
 */
enum Season2{
​
    //3. Enumeration has a limited number of objects, which are connected by commas and end with the last semicolon
    //Enumerations are placed in the header
    SPRING("spring", "Recovery of all things"),
    SUMMER("summer", "Recovery of all things 2"),
    AUTUMN("autumn", "Recovery of all things 3"),
    WINTER("winter", "Recovery of all things 4");
​
    //2. Create the attribute of Season2 and handle it with constants
    private final String SEASON_NAME;
    private final String SEASON_DESC;
​
​
    //1. Ensure that the number of objects of the class is limited
    //Then we must have a private constructor
    private Season2(String SEASON_NAME,String SEASON_DESC){
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }
​
​
    //4. Provide SEASON_NAME and session_ get method of desc
    public String getSEASON_NAME() {
        return SEASON_NAME;
    }
​
    public String getSEASON_DESC() {
        return SEASON_DESC;
    }
​
    //5. Override toString()
​
//    @Override
//    public String toString() {
//        return "Season{" +
//                "SEASON_NAME='" + SEASON_NAME + '\'' +
//                ", SEASON_DESC='" + SEASON_DESC + '\'' +
//                '}';
//    }
}

2. Enumeration classes can implement interfaces

(1) Implement the abstract method in the interface directly in the enumeration class

(2) Implemented in each enumerated object

Topics: Front-end Back-end regex