Practical Regex Examples
Real-World Regex Applications
1. Email Validation
public class EmailValidator {
private static final String EMAIL_REGEX =
"^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
public static boolean isValidEmail(String email) {
return email.matches(EMAIL_REGEX);
}
public static void main(String[] args) {
System.out.println(isValidEmail("[email protected]")); // true
System.out.println(isValidEmail("invalid-email")); // false
}
}
2. Password Strength Checker
graph TD
A[Password Validation] --> B[Length Check]
A --> C[Uppercase Letter]
A --> D[Lowercase Letter]
A --> E[Number Requirement]
A --> F[Special Character]
public class PasswordValidator {
private static final String PASSWORD_REGEX =
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,20}$";
public static boolean isStrongPassword(String password) {
return password.matches(PASSWORD_REGEX);
}
public static void main(String[] args) {
System.out.println(isStrongPassword("LabEx2023!")); // true
System.out.println(isStrongPassword("weak")); // false
}
}
Common Regex Patterns
Pattern |
Description |
Example |
\d{3}-\d{2}-\d{4} |
Social Security Number |
123-45-6789 |
^\+?1?\d{10,14}$ |
Phone Number |
+1234567890 |
\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b |
Email Validation |
[email protected] |
public class DataExtractor {
public static void extractInfo(String text) {
// Extract dates
Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher dateMatcher = datePattern.matcher(text);
while (dateMatcher.find()) {
System.out.println("Found date: " + dateMatcher.group());
}
}
public static void main(String[] args) {
String sampleText = "LabEx course started on 2023-07-15";
extractInfo(sampleText);
}
}
Advanced Regex Techniques
Splitting and Tokenizing
public class TextTokenizer {
public static void tokenizeText(String text) {
// Split by multiple delimiters
String[] tokens = text.split("[,;\\s]+");
for (String token : tokens) {
System.out.println("Token: " + token);
}
}
public static void main(String[] args) {
String input = "Java, Regex; Parsing, Techniques";
tokenizeText(input);
}
}
- Compile regex patterns for repeated use
- Use non-capturing groups when possible
- Avoid overly complex patterns
- Test performance with large datasets
Best Practices at LabEx
- Understand the specific requirements
- Test regex patterns thoroughly
- Use built-in Java regex methods
- Consider performance implications