Detailed explanation of Java regular expressions [Work Notes]

Regular expressions are often used in projects recently

Today I will write a blog post to consolidate the relevant knowledge about regular expressions with everyone.

What is a regular expression?

Regular expressions are a powerful tool for describing, matching, and manipulating strings. It can be used to validate input strings, extract strings in specific formats, replace specific parts of strings, and other operations.

Basic syntax of regular expressions

In Java, we use java.util.regexclasses provided by packages to manipulate regular expressions. Here are some commonly used regular expression syntax:

  1. .: Matches any single character (except newline).
  2. []: Define the character set and match any character in the character set.
  3. [^]: Define the reverse character set, matching characters other than any character in the character set.
  4. *: Matches the previous element zero or more times.
  5. +: Matches the previous element one or more times.
  6. ?: Matches the previous element zero or one time.
  7. {n}: Matches the previous element exactly n times.
  8. {n,}: Matches the previous element at least n times.
  9. {n,m}: Match the previous element at least n times and at most m times.
  10. (): Define subexpressions, usually used to limit the scope and priority of operators.
  11. |: Matches one of two or more expressions.

For more regular expression syntax, please refer to the official Java documentation.

Using regular expressions in Java

Java provides Patterntwo Matcherclasses to use regular expressions. Here is a simple example code:

import java.util.regex.*;

public class RegexDemo {
    public static void main(String[] args) {
        String input = "Hello, 123456!";
        String pattern = "\\d+";

        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(input);

        while (m.find()) {
            System.out.println("匹配到的数字:" + m.group());
        }
    }
}

Code analysis:

  1. inputFirst an input string and a regular expression pattern are defined pattern.
  2. Use Pattern.compile()the method to compile the regular expression into an Patternobject.
  3. Use p.matcher(input)method to create an Matcherobject for matching.
  4. Use m.find()a method loop to find portions of the input string that match a regular expression.
  5. Use m.group()method to get the matched part.

In the above example, the regular expression \\d+means match one or more numbers. Running the above code, the output is:

匹配到的数字:123456

Summarize

This blog introduces the basic syntax and usage of regular expressions in Java, and attaches a simple sample code. I hope that by reading this article, everyone will have a certain understanding of Java regular expressions.

Guess you like

Origin blog.csdn.net/weixin_39709134/article/details/132854583
Recommended