Home Java javaTutorial How to use Regex function in Java for regular expression matching

How to use Regex function in Java for regular expression matching

Jun 26, 2023 pm 02:33 PM
java: keywords related to java programming language

Regular expression is an expression for string operations, which can be used in various scenarios such as searching, replacing, and validating strings. In Java, you can use the Regex function for regular expression matching operations. This article will introduce how to use the Regex function in Java for regular expression matching.

1. Introduction to Regex function

The Regex function in Java belongs to the java.util.regex package and provides a variety of methods to perform regular expression matching operations. The core classes are Pattern and Matcher.

The Pattern class is used to define the pattern of regular expressions. Its constructor is Pattern.compile(String regex), where regex is the string representation of the regular expression.

The Matcher class is used to match strings. Its constructor is pattern.matcher(String input), where pattern is the Pattern object and input is the string that needs to be matched.

2. The syntax of regular expressions

Before matching regular expressions, you need to understand the syntax of regular expressions. The following are some basic elements of regular expression syntax:

  1. Ordinary characters: a, b, c, d and other characters represent themselves.
  2. Special characters: Backslash \ followed by specific characters can represent some special characters, such as . represents ., ? represents ?, etc.
  3. Character group: Use square brackets [] to match any character within the brackets, such as [a-z] to match any character between a to z.
  4. Exclusive character group: Use square brackets [^] to match any character except the characters in the brackets, such as 1 to match any non- Numeric characters.
  5. Quantifier: used to limit the number of occurrences of the preceding character. Commonly used quantifiers include , ,?, {m}, {m,}, {m,n}, where means Match 0 or more of the preceding characters, indicating matching of 1 or more, ? indicating matching of 0 or 1, {m} indicating that m must be matched, {m,} indicating matching of m or more, {m ,n} means matching m to n.
  6. Selectors and grouping: Use parentheses () to indicate grouping, and vertical bars | to indicate selectors, such as (ab|cd) to match ab or cd.

3. Use of Regex function

The general process of using the Regex function is: define the pattern of the regular expression (i.e. Pattern object), and perform matching operations on the strings that need to be matched. (i.e. Matcher object), query the matching results.

The following is a basic usage example of the Regex function:

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

public class RegexExample {

    public static void main(String[] args) {
        String regex = "cat";
        String input1 = "The cat is on the mat.";
        String input2 = "A cat and a dog.";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher1 = pattern.matcher(input1);
        Matcher matcher2 = pattern.matcher(input2);

        System.out.println("input1中是否包含cat:" + matcher1.find());
        System.out.println("input2中是否包含cat:" + matcher2.find());
    }
}
Copy after login

The output result is:

input1中是否包含cat:true
input2中是否包含cat:true
Copy after login

In the above code, a regular expression pattern is first defined, that is, the string " cat". Then perform matching operations on two different input strings.

In the specific matching operation, first create a Pattern object through the Pattern.compile(String regex) method, and then create a Matcher object through the matcher(String input) method of the object, and then you can use the Matcher object The find() method queries whether the input string contains a sequence of characters in the pattern.

In addition to using the find() method, the Matcher object also provides many other methods for obtaining different information about the matching results, such as the starting position of the match, the matched substring, etc.

4. Commonly used regular expression examples

  1. Check whether it is a number:
public static boolean isDigit(String str) {
    Pattern pattern = Pattern.compile("[0-9]*");
    return pattern.matcher(str).matches();
}
Copy after login
  1. Check whether it is a legal email address:
public static boolean isEmail(String str) {
    Pattern pattern = Pattern.compile("^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
    return pattern.matcher(str).matches();
}
Copy after login
  1. Check whether it is a legal mobile phone number:
public static boolean isMobileNumber(String str) {
    Pattern pattern = Pattern.compile("^1\d{10}$");
    return pattern.matcher(str).matches();
}
Copy after login
  1. Check whether it is a legal ID number:
public static boolean isIDCardNumber(String str) {
    Pattern pattern = Pattern.compile("^\d{17}[0-9xX]$");
    return pattern.matcher(str).matches();
}
Copy after login

5. Notes

  1. To ensure the correctness of the regular expression, it is recommended to verify it on the regular expression online testing tool first.
  2. When performing multiple matching operations, you should use the find() method of the Matcher object in a while loop to obtain all matching positions.
  3. When performing regular expression matching operations, be careful not to rely too much on regular expressions. You should choose the simplest method to achieve the required functions.

The above is the introduction and examples of using the Regex function in Java for regular expression matching. I hope it will be helpful to you!


  1. 0-9

The above is the detailed content of How to use Regex function in Java for regular expression matching. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

See all articles