Java Regular Expressions (Regex)
Java Regular Expressions (Regex)
Regular Expressions (Regex) are patterns used to match character combinations in strings.
In Java, regex is supported via the java.util.regex package.
Main classes:
PatternandMatcherUsed for validation, search, and text processing
1. Key Classes
| Class | Description |
|---|---|
Pattern | Compiles a regex pattern |
Matcher | Performs match operations on a string |
PatternSyntaxException | Exception for invalid regex patterns |
2. Basic Syntax
| Symbol | Meaning |
|---|---|
. | Any character |
\d | Digit (0-9) |
\D | Non-digit |
\w | Word character (a-z, A-Z, 0-9, _) |
\W | Non-word character |
\s | Whitespace |
\S | Non-whitespace |
^ | Start of string |
$ | End of string |
* | Zero or more occurrences |
+ | One or more occurrences |
? | Zero or one occurrence |
{n} | Exactly n occurrences |
{n,} | n or more occurrences |
{n,m} | Between n and m occurrences |
[] | Character class |
| ` | ` |
3. Example: Simple Match
matches()checks entire string against pattern
4. Example: Find All Matches
find()searches all occurrences in the stringgroup()returns the matched substring
5. Example: Replace Using Regex
replaceAll()replaces all matches with specified string
6. Example: Validate Email
matches()validates the entire string against pattern
7. Common Regex Patterns
| Pattern | Description |
|---|---|
\\d{10} | 10-digit number |
\\w+ | One or more word characters |
[a-zA-Z]+ | Alphabetic characters only |
\\s+ | One or more whitespace characters |
^[A-Z] | Starts with uppercase letter |
\\S+@\\S+\\.\\S+ | Simple email validation |
Best Practices
Use
Pattern.compile()when using the same regex multiple times.Escape special characters with
\\in Java strings.Use
matches()for full string validation,find()for searching within text.Consider regex readability for complex patterns.
Summary
Java supports regex using
PatternandMatcherUse regex for validation, searching, replacing, and splitting
Supports quantifiers, character classes, anchors, and groups
