Java Regular Expressions: Syntax, Examples, and Usage
This article introduces Java regular expressions, covering basic syntax, character classes, logical operators, predefined tokens, quantifiers, practical code examples, common applications such as data validation, and performance optimization tips for effective string processing in Java.
Regular expressions (Regex) are a text pattern‑matching tool widely supported in many programming languages. Java provides built‑in support for regex through the java.util.regex package, enabling convenient string processing, data validation, and text parsing.
1. Basic Syntax
Regex consists of characters and special symbols such as . (any single character), ^ (start of string), $ (end of string), * (zero or more), + (one or more), ? (zero or one), {n} (exactly n), [] (character class), | (alternation), and () (grouping).
1.1 Character Classes
Examples include [abc] , [^abc] , [a-z] , [A-Z] , [0-9] , [a-zA-Z0-9] , [a-dm-p] .
public class RegexDemo2 {
public static void main(String[] args) {
System.out.println("-----------1-------------");
System.out.println("a".matches("[abc]")); // true
System.out.println("z".matches("[abc]")); // false
System.out.println("-----------2-------------");
System.out.println("a".matches("[^abc]")); // false
System.out.println("z".matches("[^abc]")); // true
System.out.println("zz".matches("[^abc]")); // false
System.out.println("zz".matches("[^abc][^abc]")); // true
System.out.println("-----------3-------------");
System.out.println("a".matches("[a-zA-z]")); // true
System.out.println("z".matches("[a-zA-z]")); // true
System.out.println("aa".matches("[a-zA-z]")); // false
System.out.println("zz".matches("[a-zA-Z]")); // false
System.out.println("zz".matches("[a-zA-Z][a-zA-Z]")); // true
System.out.println("0".matches("[a-zA-Z]")); // false
System.out.println("0".matches("[a-zA-Z0-9]")); // true
System.out.println("-----------4-------------");
System.out.println("a".matches("[a-d[m-p]]")); // true
System.out.println("d".matches("[a-d[m-p]]")); // true
System.out.println("m".matches("[a-d[m-p]]")); // true
System.out.println("p".matches("[a-d[m-p]]")); // true
System.out.println("e".matches("[a-d[m-p]]")); // false
System.out.println("-----------5------------");
System.out.println("a".matches("[a-z&&[def]]")); // false
System.out.println("d".matches("[a-z&&[def]]")); // true
System.out.println("-----------6------------");
System.out.println("a".matches("[a-z&&[^bc]]")); // true
System.out.println("b".matches("[a-z&&[^bc]]")); // false
System.out.println("-----------7------------");
System.out.println("a".matches("[a-z&&[^m-p]]")); // true
System.out.println("m".matches("[a-z&&[^m-p]]")); // false
}
}1.2 Logical Operators
Examples: && (AND), | (OR), \ (escape).
public class Demo {
public static void main(String[] args) {
String str = "had";
// 1. lower‑case consonant start followed by "ad"
String regex = "[a-z&&[^aeiou]]ad";
System.out.println("1." + str.matches(regex));
// 2. vowel start followed by "ad"
regex = "[a|e|i|o|u]ad"; // equivalent to "[aeiou]ad"
System.out.println("2." + str.matches(regex));
}
}1.3 Predefined Characters
Tokens such as . (any character), \d (digit), \D (non‑digit), \s (whitespace), \S (non‑whitespace), \w (word character), \W (non‑word).
public class Demo {
public static void main(String[] args) {
System.out.println("你".matches("..")); // false
System.out.println("你".matches(".")); // true
System.out.println("你a".matches("..")); // true
System.out.println("a".matches("\\d")); // false
System.out.println("3".matches("\\d")); // true
System.out.println("z".matches("\\w")); // true
System.out.println("21".matches("\\w")); // false
System.out.println("2442fsfsf".matches("\\w{6,}")); // true
System.out.println("23dF".matches("[a-zA-Z0-9]{4}")); // true
System.out.println("23_F".matches("[\\w&&[^_]]{4}")); // false
}
}1.4 Quantifiers
X? : zero or one
X* : zero or more
X+ : one or more
X{n} : exactly n times
X{n,} : at least n times
X{n,m} : between n and m times (inclusive)
public class Demo {
public static void main(String[] args) {
System.out.println("2442fsfsf".matches("\\w{6,}")); // true
System.out.println("244f".matches("\\w{6,}")); // false
System.out.println("23dF".matches("[a-zA-Z0-9]{4}")); // true
System.out.println("23_F".matches("[\\w&&[^_]]{4}")); // false
}
}2. Using Regex in Java
Java’s regex functionality is provided by the java.util.regex package, primarily through the Pattern and Matcher classes.
3. Common Applications
Regex is useful for data validation such as email addresses, phone numbers, and other formatted inputs.
4. Optimization and Best Practices
Avoid overly complex patterns that cause excessive backtracking.
Pre‑compile patterns with Pattern.compile() to reuse them.
When processing large data sets, use more specific patterns to reduce unnecessary matches.
5. Summary
Regular expressions are a powerful tool for string manipulation, and Java’s built‑in support via Pattern and Matcher makes them flexible and efficient. Understanding the core syntax, common use cases, and optimization techniques can greatly improve programming productivity while avoiding performance pitfalls.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.