Real-world Applications
Data Validation and Parsing
Email Validation
public class EmailValidator {
private static final String EMAIL_REGEX =
"^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
public static boolean validateEmail(String email) {
Pattern pattern = Pattern.compile(EMAIL_REGEX);
return pattern.matcher(email).matches();
}
public static void main(String[] args) {
String[] emails = {
"[email protected]",
"invalid.email",
"[email protected]"
};
for (String email : emails) {
System.out.println(email + " is valid: " +
validateEmail(email));
}
}
}
Password Strength Checker
public class PasswordValidator {
private static final String PASSWORD_REGEX =
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,20}$";
public static boolean isStrongPassword(String password) {
Pattern pattern = Pattern.compile(PASSWORD_REGEX);
return pattern.matcher(password).matches();
}
}
Log File Processing
public class LogAnalyzer {
public static void extractIPAddresses(String logContent) {
String IP_REGEX = "\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b";
Pattern pattern = Pattern.compile(IP_REGEX);
Matcher matcher = pattern.matcher(logContent);
while (matcher.find()) {
System.out.println("Found IP: " + matcher.group());
}
}
}
CSV Parsing
public class CSVProcessor {
public static String[] splitCSVLine(String csvLine) {
return csvLine.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
}
public static void main(String[] args) {
String csvLine = "John,\"Doe, Jr.\",30,LabEx Instructor";
String[] fields = splitCSVLine(csvLine);
for (String field : fields) {
System.out.println(field);
}
}
}
Text Processing Applications
graph TD
A[Text Processing] --> B[String Cleaning]
A --> C[Data Extraction]
A --> D[Format Conversion]
B --> E[Remove Special Characters]
C --> F[Extract Specific Patterns]
D --> G[Transform Text Formats]
Common Regex Use Cases
Use Case |
Description |
Example Scenario |
Input Validation |
Ensure data meets specific criteria |
Phone number, email format |
Data Extraction |
Pull specific information |
Extracting URLs from text |
Text Transformation |
Modify string content |
Formatting user inputs |
Security |
Prevent malicious inputs |
Sanitizing user data |
- Precompile regex patterns
- Use specific matching methods
- Avoid overly complex regex
- Consider alternative parsing for complex scenarios
Error Handling and Robustness
public class SafeRegexProcessor {
public static String safeReplace(
String input,
String regex,
String replacement
) {
try {
return input.replaceAll(regex, replacement);
} catch (PatternSyntaxException e) {
System.err.println("Invalid regex pattern");
return input;
}
}
}
Advanced Regex Techniques with LabEx
By exploring these real-world applications, LabEx learners can master practical regex implementations in Java, transforming complex string processing challenges into elegant solutions.