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.pattern() Method - Complete Tutorial with Examples Java Pattern.pattern() MethodLast modified: April 20, 2025
The
The Pattern.pattern() Method Overview
The
The method signature is simple: Basic Usage of pattern()
The most straightforward use of PatternBasicExample.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternBasicExample {
public static void main(String[] args) {
String regex = "\\d{3}-\\d{2}-\\d{4}";
Pattern pattern = Pattern.compile(regex);
// Retrieve the original pattern string
String retrievedPattern = pattern.pattern();
System.out.println("Original regex: " + regex);
System.out.println("Retrieved pattern: " + retrievedPattern);
System.out.println("Are equal? " + regex.equals(retrievedPattern));
}
}
In this example, we compile a simple pattern for a social security number
format. We then use
The output demonstrates that the retrieved pattern is identical to the original
string used for compilation. This confirms that Pattern with Flags
When using pattern flags with PatternWithFlags.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternWithFlags {
public static void main(String[] args) {
String regex = "hello world";
Pattern caseInsensitivePattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
System.out.println("Pattern with flags: " + caseInsensitivePattern.pattern());
System.out.println("Flags: " + caseInsensitivePattern.flags());
}
}
This example shows that The output will show the original "hello world" string, not reflecting the case-insensitive flag that was applied. This behavior is important to understand when working with flagged patterns. Pattern.toString() vs pattern()
The Pattern class also has a PatternToStringComparison.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternToStringComparison {
public static void main(String[] args) {
String regex = "[A-Za-z]+";
Pattern pattern = Pattern.compile(regex);
System.out.println("pattern() result: " + pattern.pattern());
System.out.println("toString() result: " + pattern.toString());
// Comparing the outputs
System.out.println("Are equal? " +
pattern.pattern().equals(pattern.toString()));
}
}
This example demonstrates that both methods return the same string
representation of the regex pattern. The
In practice, you should use Using pattern() with Matcher
The PatternWithMatcher.java
package com.zetcode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternWithMatcher {
public static void main(String[] args) {
String regex = "\\b\\w{4}\\b"; // Match 4-letter words
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("This is a sample text with some words");
// Access the pattern through the Matcher
Pattern matcherPattern = matcher.pattern();
System.out.println("Matcher's pattern: " + matcherPattern.pattern());
// Find all matches
while (matcher.find()) {
System.out.println("Found: " + matcher.group() +
" matching pattern: " + matcher.pattern().pattern());
}
}
}
In this example, we demonstrate how to access the original pattern from a
Matcher object. The Matcher's This technique is particularly useful in complex applications where you might need to verify which pattern a Matcher is using or log the pattern for debugging purposes. Pattern.pattern() in Practical Applications
In real-world applications, PatternPracticalUse.java
package com.zetcode;
import java.util.regex.Pattern;
public class PatternPracticalUse {
public static void main(String[] args) {
// Simulate loading patterns from configuration
String[] patternStrings = {
"\\d{3}-\\d{3}-\\d{4}", // Phone number
"\\w+@\\w+\\.\\w+", // Simple email
"\\d{16}" // Credit card number
};
Pattern[] patterns = new Pattern[patternStrings.length];
// Compile all patterns
for (int i = 0; i < patternStrings.length; i++) {
patterns[i] = Pattern.compile(patternStrings[i]);
}
// Later in the application, we need to identify which pattern failed
String testInput = "invalid-email";
for (Pattern p : patterns) {
if (!p.matcher(testInput).matches()) {
System.out.println("Input '" + testInput +
"' doesn't match pattern: " + p.pattern());
}
}
}
}
This example simulates a common scenario where patterns are loaded from
configuration and later used for validation. When validation fails, we use
The ability to retrieve the original pattern string is invaluable for debugging and providing meaningful error messages to users or logs. Pattern.pattern() with Custom Pattern Classes
When creating custom classes that wrap Pattern objects, you can expose the
CustomPatternWrapper.java
package com.zetcode;
import java.util.regex.Pattern;
public class CustomPatternWrapper {
private final Pattern pattern;
private final String description;
public CustomPatternWrapper(String regex, String description) {
this.pattern = Pattern.compile(regex);
this.description = description;
}
public String getPatternString() {
return pattern.pattern();
}
public String getDescription() {
return description;
}
public Pattern getPattern() {
return pattern;
}
public static void main(String[] args) {
CustomPatternWrapper emailValidator = new CustomPatternWrapper(
"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
"Email address validator");
System.out.println("Validator description: " + emailValidator.getDescription());
System.out.println("Underlying pattern: " + emailValidator.getPatternString());
}
}
This example demonstrates a common design pattern where you wrap a Pattern
object in a custom class. By exposing the This approach is useful when you need to add metadata (like the description field) or additional behavior to your pattern matching functionality. SourceJava Pattern.pattern() Documentation
In this tutorial, we've explored the 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. |