Java Basics: Common APIs (Regular Expressions)

1. Regular expressions 

Regular expressions are matched one by one from left to right

The inner square brackets mean "or", && means and

The "\" backslash in Java is an escape character, so when using \d, it should be written as \\d to avoid escaping d.

In Java, \\ means \, and two bars mean one bar

2. Practice

2.1 Simple exercises

Experience: When writing a regular expression, hold a correct data and write it from left to right. 

In a regular expression, \\ represents an escape character, and \ will report an error . For example: 

Single. Indicates any character

\. will report an error

\\. represents the . character

Note: () means a group, you can download the any-rule plug-in, which contains many common regular expressions, and you can use it by right-clicking on the string.

// 利用正则表达式验证是否满足要求
        // 验证手机号(11位, 1开头)
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入手机号:");
        String phonenumber = scanner.next();
        boolean pmatches = phonenumber.matches("[1]\\d{10}");
        System.out.println(pmatches);

        // 验证座机号(至少8位, 0开头, 包括-)
        System.out.println("请输入座机号:");
        String number = scanner.next();
        boolean nmatches = number.matches("[0]\\d{2,3}-?[1-9]\\d{4,9}");
        System.out.println(nmatches);

        // 验证邮箱号(数字字母至少7位, @, 数字字母至少2位, (.c, omn)一或两次)
        System.out.println("请输入邮箱号:");
        String emailnumber = scanner.next();
        boolean ematches = emailnumber.matches("\\w{7,}@[\\w&&[^-]]{2,}([.][c][omn]{1,3})+");
        System.out.println(ematches);

2.2 Complex exercises

Note: () represents a group, and you can use | to represent or, but no spaces can be added before and after |, otherwise the verification will fail.

(?i)abc means ignoring the case of abc, AbC, abC, aBc can all be recognized successfully. 

// 验证用户名
        System.out.println("请输入用户名:");
        String username = scanner.next();
        System.out.println(username.matches("\\w{4,16}"));

        // 验证身份证号码
        System.out.println("请输入身份证号码:");
        String idcard = scanner.next();
        System.out.println(idcard.matches("[1-9]\\d{5}([1][9]\\d{2}|[2][0]([01]\\d|[2][0123]))" +
                "([0][1-9]|[1][012])([0][1-9]|[1]\\d|[2]\\d|[3][01])\\d{3}(\\d|(?i)x)"));

2.3 Summary

Guess you like

Origin blog.csdn.net/Orange_sparkle/article/details/129255096