Home Java javaTutorial Example: Use Java regular expressions to match email addresses and mobile phone numbers

Example: Use Java regular expressions to match email addresses and mobile phone numbers

Dec 26, 2023 am 08:28 AM
phone number Mail match java regular expression

Example: Use Java regular expressions to match email addresses and mobile phone numbers

Java regular expression syntax example: matching email and mobile phone numbers, specific code examples are required

Regular expression is a powerful text matching tool that can be used Extract and match required information from text. In Java, using regular expressions requires using the related classes and methods provided by the java.util.regex package. This article will introduce how to use regular expressions to match email addresses and mobile phone numbers, and give specific code examples.

1. Matching email addresses

The format of email addresses is usually "username@domain name", in which both username and domain name have certain rules and restrictions. The following is an example of a regular expression to match common email formats:

String emailRegex = "\w+@(\w+\.)+[a-zA-Z]{2,4}";
Copy after login

where:

  • "\w " matches one or more letters, numbers, or underscores, Represents the part of the user name;
  • "(\w .) " matches one or more letters, numbers, or underscores followed by a dot, representing the part of the domain name;
  • "[a-zA- Z]{2,4}" matches 2 to 4 letters, indicating the domain name suffix.

Use the above regular expression to quickly determine whether a string conforms to the email format. The sample code is as follows:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {
    private static final String EMAIL_REGEX = "\w+@(\w+\.)+[a-zA-Z]{2,4}";

    public static boolean isValidEmail(String email) {
        Pattern pattern = Pattern.compile(EMAIL_REGEX);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static void main(String[] args) {
        String email = "test123@example.com";
        if (isValidEmail(email)) {
            System.out.println(email + "是一个有效的邮箱地址");
        } else {
            System.out.println(email + "不是一个有效的邮箱地址");
        }
    }
}
Copy after login

Run the above code to get the following output:

test123@example.com是一个有效的邮箱地址
Copy after login

2. Matching mobile phone numbers

Mobile phone numbers generally consist of 11 digits, starting with 1. The following is an example of a regular expression to match the common mobile phone number format:

String phoneRegex = "1[3-9]\d{9}";
Copy after login

where:

  • "1" means the mobile phone number starts with 1;
  • "[3-9]" means that the second digit can be any number between 3 and 9;
  • "\d{9}" means that the following 9 digits can be any number.

Use the above regular expression to quickly determine whether a string conforms to the mobile phone number format. The sample code is as follows:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneValidator {
    private static final String PHONE_REGEX = "1[3-9]\d{9}";

    public static boolean isValidPhone(String phone) {
        Pattern pattern = Pattern.compile(PHONE_REGEX);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    public static void main(String[] args) {
        String phone = "13812345678";
        if (isValidPhone(phone)) {
            System.out.println(phone + "是一个有效的手机号码");
        } else {
            System.out.println(phone + "不是一个有效的手机号码");
        }
    }
}
Copy after login

Run the above code to get the following output:

13812345678是一个有效的手机号码
Copy after login

Summary:

Through the above example code, we show how to use regular expressions to match email addresses and mobile phone numbers. Regular expressions are a powerful tool that can be used to handle a variety of text matching problems. In practical applications, we can adjust the specific rules of regular expressions as needed to adapt to various data format requirements. I hope this article helps you learn and use regular expressions.

The above is the detailed content of Example: Use Java regular expressions to match email addresses and mobile phone numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

gate.io registration tutorial gate.io registration tutorial Mar 31, 2025 pm 11:09 PM

This article provides a detailed Gate.io registration tutorial, covering every step from accessing the official website to completing registration, including filling in registration information, verifying, reading user agreements, etc. The article also emphasizes security measures after successful registration, such as setting up secondary verification and completing real-name authentication, and gives tips from beginners to help users safely start their digital asset trading journey.

gate.io latest registration tutorial for beginners gate.io latest registration tutorial for beginners Mar 31, 2025 pm 11:12 PM

This article provides newbies with detailed Gate.io registration tutorials, guiding them to gradually complete the registration process, including accessing the official website, filling in information, identity verification, etc., and emphasizes the security settings after registration. In addition, the article also mentioned other exchanges such as Binance, Ouyi and Sesame Open Door. It is recommended that novices choose the right platform according to their own needs, and remind readers that digital asset investment is risky and should invest rationally.

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

The latest registration tutorial for gate.io web version The latest registration tutorial for gate.io web version Mar 31, 2025 pm 11:15 PM

This article provides a detailed Gate.io web version latest registration tutorial to help users easily get started with digital asset trading. The tutorial covers every step from accessing the official website to completing registration, and emphasizes security settings after registration. The article also briefly introduces other trading platforms such as Binance, Ouyi and Sesame Open Door. It is recommended that users choose the right platform according to their own needs and pay attention to investment risks.

Binance binance computer version entrance Binance binance computer version PC official website login entrance Binance binance computer version entrance Binance binance computer version PC official website login entrance Mar 31, 2025 pm 04:36 PM

This article provides a complete guide to login and registration on Binance PC version. First, we explained in detail the steps for logging in Binance PC version: search for "Binance Official Website" in the browser, click the login button, enter the email and password (enable 2FA to enter the verification code) to log in. Secondly, the article explains the registration process: click the "Register" button, fill in the email address, set a strong password, and verify the email address to complete the registration. Finally, the article also emphasizes account security, reminding users to pay attention to the official domain name, network environment, and regularly updating passwords to ensure account security and better use of various functions provided by Binance PC version, such as viewing market conditions, conducting transactions and managing assets.

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

The latest registration portal for Ouyi official website The latest registration portal for Ouyi official website Mar 21, 2025 pm 05:54 PM

As the world's leading digital asset trading platform, Ouyi OKX attracts many investors with its rich trading products, strong security guarantees and convenient user experience. However, the risks of network security are becoming increasingly severe, and how to safely register the official Ouyi OKX account is crucial. This article will provide the latest registration portal for Ouyi OKX official website, and explain in detail the steps and precautions for safe registration, including how to identify the official website, set a strong password, enable two-factor verification, etc., to help you start your digital asset investment journey safely and conveniently. Please note that there are risks in digital asset investment, please make cautious decisions.

See all articles