Core Components of java.util.regex
Java's regular expression functionality is provided through the java.util.regex package, which consists of three primary classes:
- Pattern: Represents a compiled regular expresison pattern. Instances are created using the static
compile()method rather than constructors. - Matcher: Performs match operations on character sequences using a compiled pattern. Obtained by calling the
matcher()method on a Pattern instance. - PatternSyntaxException: An unchecked exception that indicates a syntax error in the regular expression pattern.
Example implementation for QQ number validation:
import java.util.Scanner;
import java.util.regex.Pattern;
class ValidationDemo {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your QQ number:");
String userInput = input.nextLine();
System.out.println("Validation result: " + validateQQ(userInput));
}
private static boolean validateQQ(String number) {
return Pattern.matches("[1-9]{1}\\d{4,14}", number);
}
}
Capture Groups and Matching
Groups allow treating multiple characters as a single unit by enclosing them in parentheses. Groups are numbered from left to right based on opening parentheses position.
The groupCount() method returns the number of capturing groups, excluding group 0 which represents the entire match.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GroupExample {
public static void main(String[] args) {
String text = "This order was placed for QT3000! OK?";
String regex = "(\\D*)(\\d+)(.*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
System.out.println("Prefix: " + matcher.group(1));
System.out.println("Numbers: " + matcher.group(2));
System.out.println("Suffix: " + matcher.group(3));
}
}
}
Output:
Full match: This order was placed for QT3000! OK?
Prefix: This order was placed for QT
Numbers: 3000
Suffix: ! OK?
Character Classes and Special Sequences
Regular expressions combine literal characters with metacharacters that have special meanings:
Literal Characters: Standard alphanumeric and punctuation characters that match themselves exactly.
Metacharacters:
.: Matches any character except line terminators\\d: Matches any digit (0-9)\\w: Matches word characters (letters, digits, underscore)\\s: Matches whitespace characters[...]: Matches any character with in brackets^: Anchors match to beginning of input$: Anchors match to end of input
Important note about escape sequences: In Java strings, backslashes must be escaped, so \\d becomes "\\\\d" in string literals.
String Manipulation Methods
Java provides several methods for working with regular expressions:
matches(String regex): Tests if entire string matches patternsplit(String regex): Divides string at pattern matchesreplaceAll(String regex, String replacement): Replaces all matching substrings
Common Regular Expression Patterns
Quantifiers control how many times preceding elements can occur:
*: Zero or more occurrences+: One or more occurrences?: Zero or one occurrence{n}: Exactly n occurrences{n,}: At least n occurrences{n,m}: Between n and m occurrences
Additional constructs:
?after quantifiers enables non-greedy matching(pattern): Capturing group(?:pattern): Non-capturing group(?=pattern): Positive lookahead assertion(?!pattern): Negative lookahead assertionx|y: Alternation, matches either x or y
Boundary matchers:
\\b: Word boundary\\B: Non-word boundary^: Beginning of line$: End of line
Predefined character classes:
\\d: Digits [0-9]\\D: Non-digits [^0-9]\\w: Word characters [a-zA-Z_0-9]\\W: Non-word characters\\s: Whitepsace characters\\S: Non-whitespace characters
Unicode and specific patterns:
\\unnnn: Unicode character (four hex digits)[\\u4e00-\\u9fa5]: Chinese characters[^�-ÿ]: Double-byte characters\\w+([-.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*: Email addresseshttp://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?: URLs