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.regex
classes provided by packages to manipulate regular expressions. Here are some commonly used regular expression syntax:
.
: Matches any single character (except newline).[]
: Define the character set and match any character in the character set.[^]
: Define the reverse character set, matching characters other than any character in the character set.*
: Matches the previous element zero or more times.+
: Matches the previous element one or more times.?
: Matches the previous element zero or one time.{n}
: Matches the previous element exactly n times.{n,}
: Matches the previous element at least n times.{n,m}
: Match the previous element at least n times and at most m times.()
: Define subexpressions, usually used to limit the scope and priority of operators.|
: 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 Pattern
two Matcher
classes 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:
input
First an input string and a regular expression pattern are definedpattern
.- Use
Pattern.compile()
the method to compile the regular expression into anPattern
object. - Use
p.matcher(input)
method to create anMatcher
object for matching. - Use
m.find()
a method loop to find portions of the input string that match a regular expression. - 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.