Java Regular Expressions (RegEx)
Regular Expressions (RegEx) in Java provide a powerful way to perform pattern matching and manipulate strings. Java's java.util.regex
package contains classes for working with regular expressions, primarily Pattern
and Matcher
.
1. Key Classes
Pattern
: Represents a compiled regular expression.Matcher
: An engine that performs match operations on a character sequence.
2. Basic Usage
To use RegEx in Java, you compile a pattern and then create a matcher to perform operations.
Example: Checking if a String Matches a Pattern
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegExExample {
public static void main(String[] args) {
String text = "hello123";
String patternString = "\\w+\\d+";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
System.out.println("Pattern matches!");
} else {
System.out.println("Pattern does not match.");
}
}
}
// Output: Pattern matches!
3. Common Methods
matches()
: Attempts to match the entire input sequence against the pattern.find()
: Attempts to find the next subsequence that matches the pattern.replaceAll()
: Replaces every subsequence that matches the pattern with a replacement string.
Example: Finding All Occurrences
String text = "Email me at example@test.com or admin@test.org";
String patternString = "\\b\\w+@\\w+\\.\\w+\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("Found email: " + matcher.group());
}
// Output:
// Found email: example@test.com
// Found email: admin@test.org
4. Predefined Character Classes
\d
: A digit (0-9).\w
: A word character (letters, digits, underscore).\s
: A whitespace character..
: Any character.
5. Quantifiers
*
: Matches zero or more occurrences.+
: Matches one or more occurrences.?
: Matches zero or one occurrence.{n}
: Matches exactly n occurrences.
6. Key Takeaways
- Regular expressions provide powerful pattern matching capabilities.
- Use
Pattern
andMatcher
classes for regex operations. - Understand regex syntax and constructs for effective use.
- Be cautious with special characters; use double backslashes
\\
in Java strings.