Regex in Java - Complete Guide
A Powerful Tool for String Matching, Searching & Validation
๐น What is Regex?
Regex (short for Regular Expression) is a sequence of characters that defines a search pattern. In Java, Regex is widely used for validating inputs, searching text, and string manipulation.
๐ Example: Check if an email is valid, extract numbers from text, or replace all spaces with dashes.
๐น Java Regex Package
Java provides java.util.regex package for working with regular expressions. It contains mainly two classes:
- Pattern – Used to define (compile) the regex.
- Matcher – Used to perform matching operations on text.
๐น Basic Example
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String regex = "[a-z]+"; // one or more lowercase letters
String input = "hello123";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found: " + matcher.group());
} else {
System.out.println("No match");
}
}
}
Output:
Match found: hello
๐น Common Regex Patterns in Java
| Regex Pattern | Description | Example Match |
|---|---|---|
| [0-9]+ | One or more digits | 12345 |
| [a-zA-Z]+ | Only alphabets | Hello |
| \\d{10} | Exactly 10 digits (Phone Number) | 9876543210 |
| ^\\w+@\\w+\\.\\w+$ | Simple Email Validation | user@example.com |
| \\s+ | One or more spaces | " " |
| ^a.*z$ | String starting with 'a' and ending with 'z' | alphabetz |
๐น Useful Regex Methods
Pattern pattern = Pattern.compile("regex");
Matcher matcher = pattern.matcher("your string");
// Methods
matcher.find(); // Returns true if match found
matcher.group(); // Returns matched substring
matcher.matches(); // Checks full string matches regex
matcher.replaceAll("new"); // Replaces all matches
๐น Real-life Use Cases
- ✔ Validate Email & Phone Numbers
- ✔ Check Strong Passwords
- ✔ Extract numbers from text
- ✔ Replace unwanted characters
- ✔ Split a string using patterns
✅ In short: Regex in Java is a powerful tool to match, search, validate, and manipulate strings effectively.
Comments
Post a Comment