SoFunction
Updated on 2025-04-24

Example of Java commonly used regular expressions (ID number, email number, mobile phone number) format verification code

Example of Java commonly used regular expressions (ID number, email number, mobile phone number) format verification code

Updated: April 24, 2025 10:16:47 Author: Lang Jiutian
This article mainly introduces relevant information on Java's commonly used regular expression format verification, explains the use of regular expressions to verify ID number, email address and mobile phone number, and allows input to be empty strings. Detailed code examples are given. Friends who need it can refer to it.

Regular expression of ID number

To use regular expressions to verify the ID number in Java, and allow input to be an empty string, you can add matching to the empty string based on the original ID number verification regular expression. Here is the sample code:

import ;
import ;

public class IDCardValidatorWithEmpty {
    // Define a regular expression that supports ID number verification for empty strings    private static final String ID_CARD_REGEX = "^$|(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)";
    private static final Pattern ID_CARD_PATTERN = (ID_CARD_REGEX);

    /**
      * Method to verify the ID number, allowing empty strings
      * @param idCard ID number to be verified
      * @return Return true if the ID number is formatted correctly or is an empty string, otherwise return false
      */
    public static boolean isValidIDCard(String idCard) {
        Matcher matcher = ID_CARD_PATTERN.matcher(idCard);
        return ();
    }

    public static void main(String[] args) {
        // 15-digit ID number used for testing        String idCard15 = "110105880620517";
        // 18-digit ID number used for testing        String idCard18 = "11010519880620517X";
        // Invalid ID number        String invalidIdCard = "123456789012345678";
        // Empty string        String emptyIdCard = "";

        // Call the verification method and output the result        (idCard15 + " Is it a valid ID number: " + isValidIDCard(idCard15));
        (idCard18 + " Is it a valid ID number: " + isValidIDCard(idCard18));
        (invalidIdCard + " Is it a valid ID number: " + isValidIDCard(invalidIdCard));
        ("Is an empty string allowed: " + isValidIDCard(emptyIdCard));
    }
}

Code explanation

Regular expressions

^$|(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)
  • ^$: Used to match empty strings,^Represents the starting position of the string,$Represents the end position of the string, and combining the two means an empty string.
  • |: This is a logic or operator that separates different matching rules.
  • (^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$): This part is used to match 15-digit ID number, and the detailed explanation is as follows:
    • [1-9]\\d{7}: The first 8 digits of the ID number, the first digit cannot be 0.
    • ((0\\d)|(1[0-2])): represents month, with a range of 01 - 12.
    • (([0|1|2]\\d)|3[0-1]): represents date, range is 01 - 31.
    • \\d{3}: The last 3 digits sequence code.
  • (^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$): Used to match 18-digit ID number, the specific explanation is as follows:
    • [1-9]\\d{5}: The first 6 digits region code, the first digit cannot be 0.
    • [1-9]\\d{3}: The first digit cannot be 0 for the next 4 years.
    • ((0\\d)|(1[0-2]))and(([0|1|2]\\d)|3[0-1]): Represents month and date respectively.
    • ((\\d{4})|\\d{3}[Xx]): The last 4 digits, which may be 4 digits or the first 3 digits plus the last digitXorx

Method isValidIDCard

This method uses the help ofMatcherObject to check whether the input string matches the regular expression, if it matches, it returnstrue, otherwise returnfalse

Things to note

  • This regular expression can only verify whether the format of the ID number is correct and cannot verify its authenticity and validity.
  • For special cases such as the February date range of leap years, regular expressions cannot be accurately verified. If stricter verification is required, other logic may be combined.

Verify the regular expression of the mailbox

In Java, to verify mailboxes and allow empty strings, you can add matching rules to empty strings based on regular expressions originally used to verify mailbox formats. Here is the sample code:

import ;
import ;

public class EmailValidatorWithEmpty {
    // Define a mailbox check regular expression that supports empty strings    private static final String EMAIL_REGEX = "^$|^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    private static final Pattern EMAIL_PATTERN = (EMAIL_REGEX);

    /**
      * Method to verify mailbox, allowing empty strings
      * @param email The email address to be verified
      * @return Return true if the mailbox is formatted correctly or is an empty string, otherwise return false
      */
    public static boolean isValidEmail(String email) {
        Matcher matcher = EMAIL_PATTERN.matcher(email);
        return ();
    }

    public static void main(String[] args) {
        // Valid email        String validEmail = "example@";
        // Invalid mailbox        String invalidEmail = "";
        // Empty string        String emptyEmail = "";

        (validEmail + " Is it a valid email address: " + isValidEmail(validEmail));
        (invalidEmail + " Is it a valid email address: " + isValidEmail(invalidEmail));
        ("Is an empty string allowed: " + isValidEmail(emptyEmail));
    }
}

Code explanation

Regular expressions

^$|^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$
  • ^$: Used to match empty strings.^Denotes the starting position of the string.$Denotes the end position of the string. The combination of the two represents an empty string.
  • |: Logical or operator, used to separate different matching rules.
  • ^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$: Used to match the normal mailbox format, the specific explanation is as follows:
    • ^: Indicates the beginning of the string.
    • [a-zA-Z0-9_+&*-]+: Match the beginning of the mailbox username, allowing letters, numbers, underscores, plus signs, hyphens, asterisks, and verson signs.
    • (?:\\.[a-zA-Z0-9_+&*-]+)*: Match the dot numbers that may appear in the user name and the characters that follow them.(?: ... )is a non-capturing group,*It means that the previous part can appear 0 or more times.
    • @: Match the email address@Symbol.
    • (?:[a-zA-Z0-9-]+\\.)+: Match the domain name part, allow letters, numbers, and hyphens, and can have multiple subdomains, each subdomain followed by a dot.
    • [a-zA-Z]{2,7}: Match the top-level domain name, which consists of 2 to 7 letters.
    • $: Indicates the end of the string.

Method isValidEmail

This method passesMatcherObject checks whether the input string matches the regular expression, and if it matches, it returnstrue, otherwise returnfalse

Things to note

  • Although this regular expression can verify the basic format of the email address, it cannot guarantee that the email address is real and usable.
  • For some special email addresses, such as those with international domain names, more complex regular expressions may be required for accurate verification.

Regular expression of mobile phone number

The following provides you with Java code examples that provide verification regular expressions for mobile phone numbers and general mobile phone numbers in mainland China, and also supports empty string verification.

Mainland China mobile phone number verification (supports empty strings)

import ;
import ;

public class ChinesePhoneValidatorWithEmpty {
    // Define a Chinese mainland mobile phone number verification regular expression that supports empty strings    private static final String PHONE_REGEX = "^$|^1[3-9]\\d{9}$";
    private static final Pattern PHONE_PATTERN = (PHONE_REGEX);

    /**
      * Method to verify mobile phone numbers in mainland China, allowing empty strings
      * @param phone number to be verified
      * @return Return true if the phone number is formatted correctly or is an empty string, otherwise return false
      */
    public static boolean isValidChinesePhone(String phone) {
        Matcher matcher = PHONE_PATTERN.matcher(phone);
        return ();
    }

    public static void main(String[] args) {
        // Valid mobile phone number        String validPhone = "13800138000";
        // Invalid mobile phone number        String invalidPhone = "23800138000";
        // Empty string        String emptyPhone = "";

        (validPhone + "Is it a valid mainland Chinese mobile number: " + isValidChinesePhone(validPhone));
        (invalidPhone + "Is it a valid mainland Chinese mobile number: " + isValidChinesePhone(invalidPhone));
        ("Is an empty string allowed: " + isValidChinesePhone(emptyPhone));
    }
}

Code explanation

  • Regular expression^$|^1[3-9]\\d{9}$
    • ^$: Used to match empty strings,^Indicates the beginning of the string,$Indicates that the string ends, and the combination of the two matches the empty content.
    • |: Logical or operator, separating different matching rules.
    • ^1[3-9]\\d{9}$: Used to match 11-digit mobile phone numbers in mainland China. The mobile phone numbers start with 1, the second digit is a number in 3 - 9, followed by a 9-digit number.

Universal mobile phone number verification (supports empty strings)

import ;
import ;

public class GeneralPhoneValidatorWithEmpty {
    // Define a general mobile phone number verification regular expression that supports empty strings    private static final String GENERAL_PHONE_REGEX = "^$|^\\+?[1-9]\\d{1,14}$";
    private static final Pattern GENERAL_PHONE_PATTERN = (GENERAL_PHONE_REGEX);

    /**
      * Method to verify common mobile phone number, allowing empty strings
      * @param phone number to be verified
      * @return Return true if the phone number is formatted correctly or is an empty string, otherwise return false
      */
    public static boolean isValidGeneralPhone(String phone) {
        Matcher matcher = GENERAL_PHONE_PATTERN.matcher(phone);
        return ();
    }

    public static void main(String[] args) {
        // Valid universal mobile phone number        String validGeneralPhone = "+8613800138000";
        // Invalid universal mobile phone number        String invalidGeneralPhone = "+0123456789";
        // Empty string        String emptyGeneralPhone = "";

        (validGeneralPhone + " Is it a valid universal mobile number: " + isValidGeneralPhone(validGeneralPhone));
        (invalidGeneralPhone + " Is it a valid universal mobile number: " + isValidGeneralPhone(invalidGeneralPhone));
        ("Is an empty string allowed: " + isValidGeneralPhone(emptyGeneralPhone));
    }
}

Code explanation

  • Regular expression^$|^\\+?[1-9]\\d{1,14}$
    • ^$: Match empty string.
    • |: Logical or operator.
    • ^\\+?[1-9]\\d{1,14}$: Used to match common mobile phone numbers,\\+?Represents the country code before+Numbers are optional,[1-9]It means that the first position of the mobile phone number cannot be 0.\\d{1,14}It means that 1 to 14 numbers can be followed, meeting the maximum 15-digit mobile phone number (including country code) stipulated by the International Telecommunications Union.

Things to note

  • Regular expressions can only verify the format of the mobile phone number and cannot determine whether the mobile phone number is real and available.
  • The mobile phone number rules may be adjusted over time and operators, and regular expressions need to be updated according to actual conditions.

Summarize

This is the article about the format verification of Java commonly used regular expressions (ID number, email number, mobile phone number) in this article. For more related Java regular expression format verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • java
  • Regular expressions
  • check

Related Articles

  • The entire process of memory layout of Java objects

    This article mainly introduces the entire memory layout process of Java objects, which has good reference value and hopes to be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2022-05-05
  • How to quickly create projects using the Maven plugin

    This article mainly introduces how to quickly create projects using the Maven plug-in. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor
    2018-09-09
  • Java code to implement hotel management system

    This article mainly introduces the Java code to implement the hotel management system in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2022-05-05
  • java sorting algorithm merge sorting

    This article mainly explains the merger and sorting in the sorting algorithm. The article uses a large number of pictures and codes to explain in detail. Interested friends can learn this article, which I believe can help you.
    2021-09-09
  • Solve the problem of TimeUtild not being used in JDK21

    When using TimeUtil, the problem may be caused by incompatibility of the IDE version. Upgrading IDEA to 2023.2 or above can solve this problem. The detailed steps can be requested for the installation package through the comment area or downloaded directly from the official website to share personal experience. I hope it will be helpful to everyone.
    2024-10-10
  • Java Basics: Use of BufferedReader Streaming

    This article mainly introduces the use of BufferedReader streams, which are of good reference value and hope it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2021-12-12
  • Springboot project implementation excludes classes from @ComponentScan

    This article mainly introduces the implementation of Springboot project to exclude classes from @ComponentScan, which has good reference value and hopes it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2021-11-11
  • Spring explains object-oriented to face-oriented tangents in detail

    Object-oriented programming is a programming method. The implementation of this programming method requires the use of "classes" and "objects". Therefore, object-oriented programming is actually the use of "classes" and "objects". Symbol-oriented programming. Simply put, it is to dynamically cut the code into the specified method of the class and the programming idea of ​​specifying the location of the class. It is the programming idea of ​​tangent-oriented programming.
    2022-08-08
  • java io file operation Six ways to read data from a file

    This article mainly introduces six methods to read data from files in Java io operation summary. Friends in need can learn from it for reference. I hope it can be helpful. I wish you more progress and get promoted as soon as possible to get a salary increase.
    2022-03-03
  • How to get the local operating system process list

    This article introduces how to obtain information about the current running system process in Java. Friends who need it can refer to it.
    2015-07-07

Latest Comments