Some examples of Java regular expressions

example:

Match all ID numbers in the string

public static void main(String[] args) {
        //正则表达式
        String regex = "([1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx])|([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3})";
        String str = "410225192205056614-s41022519650505402X-s41022519650505123Xs41022519650505123Xs41022519650505123Xs41022519650505123X";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        while (m.find()) {
            System.out.println(m.group());
        }
    }

 

Match all the ID numbers that appear for the first time in the string

public static void main(String[] args) {
        //正则表达式
        String regex = "([1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx])|([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3})";
        String str = "410225192205056614-s41022519650505402X-s41022519650505123Xs41022519650505123Xs41022519650505123Xs41022519650505123X";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        m.find();
        System.out.println(m.group());
    }

Expression example

//身份证号的表达式
String regex = "([1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx])|([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3})";

//Email 邮箱的表达式
String regex = "\\w+@\\w+\\.(com\\.cn)|\\w+@\\w+\\.(com|cn)";

 

Last edited record-August 28, 2020 11:24:47

 

Sincerely

Guess you like

Origin blog.csdn.net/weixin_40195422/article/details/107036492