java- regular expression exercises

Regular Expressions practice

Determine identity: either 15 or 18 digits, the last one can be a letter, and asked them to write the program date.

Copy the code
static void main public (String [] args) { 
        testID_Card (); 
    } 

    public static void testID_Card () { 
        // test whether a valid ID number 
        String [] = {STRs "130681198712092019", "13068119871209201x", 
                "13068119871209201" , "123456789012345", "12345678901234x", 
                "1234567890123"}; 
        // prepare regular expressions (identity card 15 and 18 are two, the last one identity may be letters) 
        String regex = "(\\ d 14} \\ W {) | D \\ \\ {W}. 17 "; 
        // ready to match, it is determined whether the input is all right 
        Pattern regular = Pattern.compile (regex); // Create a matching rule Patter 

        the StringBuilder new new SB = the StringBuilder (); 
        // through all strings to be matched 
        for (int i = 0; i <strs.length; i++) {

            Matcher matcher = regular.matcher (strs [i ]); // Create a Matcher 
            sb.append ( "ID:"); 
            sb.append (STRs [I]); 
            sb.append ( "Match:"); 
            SB .append (matcher.matches ()); 
            System.out.println (sb.toString ()); 
            sb.delete (0, sb.length ()); // Clear method StringBuilder 
        } 

        GetBirthDay (STRs); 

    } 

    Private void GetBirthDay static (String [] STRs) { 
        System.out.println ( "ready to get the date of birth"); 
        // prepare validation rules 
        Pattern BirthDayRegular = Pattern.compile ( "(\\ d {6}) (\\ d {8}) (*). "); 
        // * together any number of means does not contain newline characters.  
        the Pattern YearMonthDayRegular the Pattern =
                .compile ("(\\d{4})(\\d{2})(\\d{2})");
        for (int I = 0; I <strs.length; I ++) { 
            Matcher Matcher = BirthDayRegular.matcher (STRs [I]); 

            IF (matcher.matches ()) { 
                Matcher matcher2 = YearMonthDayRegular 
                        .matcher (Matcher.group (2 )); 
                IF (matcher2.matches ()) { 
                    System.out.println (STRs [I] + "the date of birth decomposition:" + "in" + matcher2.group (1) + "month:" 
                            + matcher2.group (2) + "day:" + matcher2.group (. 3)); 

                } 
            } 
        } 

    }
Copy the code

Guess you like

Origin www.cnblogs.com/wuqiance/p/11605027.html