GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java Pattern Class - Complete Tutorial with Examples Java Pattern ClassLast modified: April 20, 2025
The Pattern provides static methods to compile regular expressions and create Pattern objects. Once compiled, a Pattern can be used to create Matcher objects that perform match operations. The class is part of Java's regex package. Pattern Class OverviewPattern is a final class that cannot be instantiated directly. It provides methods to compile regex patterns and perform various matching operations. The class works closely with the Matcher class to provide regex functionality.
The Basic Pattern Matching
Pattern matching allows you to determine if a string conforms to a specific
regular expression (regex) pattern. The PatternBasic.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternBasic {
public static void main(String[] args) {
// Sample input string to be matched
String input = "Welcome to Java!";
// Regex pattern to match any string starting with "Welcome"
String regex = "Welcome.*";
// Using the static 'matches' method for a quick check
boolean isMatch = Pattern.matches(regex, input);
System.out.println("Static matches method: " + isMatch);
// Compiling the regex pattern for reuse
Pattern compiledPattern = Pattern.compile(regex);
isMatch = compiledPattern.matcher(input).matches();
System.out.println("Using compiled pattern: " + isMatch);
}
}
In this example, we demonstrate two approaches to pattern matching in Java:
The
Both methods return Exploring Pattern Flags in Java
Pattern flags provide flexibility in matching behaviors when using regular
expressions (regex). They can make matching case-insensitive, enable multiline
processing, and introduce other customizations. Flags are specified as the
second argument to the PatternFlags.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternFlags {
public static void main(String[] args) {
// Sample input string
String input = "Java is powerful\nProgramming is fun!";
// Regex to match a line containing "programming" (case-insensitive)
String regex = "^programming.*$";
// Case insensitive matching
Pattern caseInsensitive = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
boolean isCaseInsensitiveMatch = caseInsensitive.matcher(input).find();
System.out.println("Case insensitive match: " + isCaseInsensitiveMatch);
// Multiline mode (^ and $ match start and end of each line)
Pattern multiline = Pattern.compile(regex,
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
boolean isMultilineMatch = multiline.matcher(input).find();
System.out.println("Multiline match: " + isMultilineMatch);
}
}
In this example, we showcase two frequently used pattern flags:
These flags can be combined using the bitwise OR operator to create more versatile matching scenarios. Pattern Splitting
The PatternSplit.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternSplit {
public static void main(String[] args) {
String input = "apple,orange,,banana, grape";
String regex = "\\s*,\\s*";
Pattern pattern = Pattern.compile(regex);
String[] fruits = pattern.split(input);
System.out.println("Split results:");
for (String fruit : fruits) {
System.out.println("'" + fruit + "'");
}
// Split with limit
String[] limited = pattern.split(input, 3);
System.out.println("\nSplit with limit 3:");
for (String fruit : limited) {
System.out.println("'" + fruit + "'");
}
}
}
This example splits a string at commas, ignoring optional whitespace. The first split processes the entire input. The second split uses a limit parameter to control the maximum number of splits. Empty elements are preserved in the result. Pattern Matcher Operations
The PatternMatcher.java
package com.zetcode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatcher {
public static void main(String[] args) {
String input = "Prices: $10.50, $5.25, $8.75";
String regex = "\\$\\d+\\.\\d{2}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
System.out.println("All prices:");
while (matcher.find()) {
System.out.println(matcher.group());
}
// Replacement example
String result = matcher.replaceAll("PRICE");
System.out.println("\nAfter replacement: " + result);
}
}
This example finds all dollar amounts in a string using a Matcher. The
Named Capturing Groups
Pattern supports named capturing groups using the PatternNamedGroups.java
package com.zetcode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternNamedGroups {
public static void main(String[] args) {
String input = "John Doe, age 30; Jane Smith, age 25";
String regex = "(?<name>[A-Za-z ]+), age (?<age>\\d+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Name: " + matcher.group("name"));
System.out.println("Age: " + matcher.group("age"));
System.out.println("Full match: " + matcher.group(0) + "\n");
}
}
}
This example extracts names and ages using named groups. The pattern defines two
named groups: "name" and "age". The Pattern Quote
The PatternQuote.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternQuote {
public static void main(String[] args) {
String input = "File path: C:\\Program Files\\Java";
String literal = "C:\\Program Files\\Java";
// Without quoting (won't work due to special chars)
try {
boolean matches = Pattern.matches(".*" + literal + ".*", input);
System.out.println("Without quote: " + matches);
} catch (Exception e) {
System.out.println("Error without quote: " + e.getMessage());
}
// With quoting
String quoted = Pattern.quote(literal);
boolean matches = Pattern.matches(".*" + quoted + ".*", input);
System.out.println("With quote: " + matches);
}
}
This example shows the difference between using and not using Pattern Predicate
Java 11 added the PatternPredicate.java
package com.zetcode;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class PatternPredicate {
public static void main(String[] args) {
Pattern emailPattern = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
Pattern.CASE_INSENSITIVE);
Stream.of("[email protected]", "invalid", "[email protected]")
.filter(emailPattern.asPredicate())
.forEach(System.out::println);
// asMatchPredicate requires full string match
System.out.println("\nUsing asMatchPredicate:");
Stream.of("[email protected]", "prefix [email protected] suffix")
.filter(emailPattern.asMatchPredicate())
.forEach(System.out::println);
}
}
This example demonstrates both predicate methods. SourceJava Pattern Class Documentation In this article, we've covered the essential methods and features of the Java Pattern class. Understanding these concepts is crucial for working with regular expressions in Java applications. AuthorMy name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |