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

How to use Regex function in Java for regular expression matching

WBOY
WBOYOriginal
2023-06-26 14:33:191600browse

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());
    }
}

The output result is:

input1中是否包含cat:true
input2中是否包含cat:true

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();
}
  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();
}
  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();
}
  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();
}

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:
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