Mastering Regular Expressions for Text Processing

Regular expressions provide powerful pattern matching capabilities for text processing. Here's an example demonstrating their efficiency compared to manual string parsing:

public class TextProcessor {
    public static void main(String[] args) {
        String sampleText = "Java was originally developed by James Gosling at Sun Microsystems in 1991. " +
               "The language was initially called Oak after an oak tree outside Gosling's office. " +
               "In 1995, it was renamed to Java and version 1.0 was released to the public.";
        
        // Extract all numeric sequences
        Pattern numberPattern = Pattern.compile("\\d+");
        Matcher numberMatcher = numberPattern.matcher(sampleText);
        
        while(numberMatcher.find()) {
            System.out.println("Numeric value: " + numberMatcher.group());
        }
        
        // Extract all capitalized words
        Pattern wordPattern = Pattern.compile("[A-Z][a-z]+");
        Matcher wordMatcher = wordPattern.matcher(sampleText);
        
        while(wordMatcher.find()) {
            System.out.println("Capitalized word: " + wordMatcher.group());
        }
    }
}

Core Regular Expression Cocnepts

Pattern Matching Fundamentals

Regular expressions work by creating pattern objects that define matching rules:

public class PatternMatching {
    public static void main(String[] args) {
        String logData = "Error 404 occurred at 10:30:45 on 2023-05-15";
        
        // Match time patterns (HH:MM:SS)
        Pattern timePattern = Pattern.compile("\\d{2}:\\d{2}:\\d{2}");
        Matcher timeMatcher = timePattern.matcher(logData);
        
        // Match date patterns (YYYY-MM-DD)
        Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
        Matcher dateMatcher = datePattern.matcher(logData);
        
        while(timeMatcher.find()) {
            System.out.println("Time found: " + timeMatcher.group());
        }
        
        while(dateMatcher.find()) {
            System.out.println("Date found: " + dateMatcher.group());
        }
    }
}

Advanced Regular Expression Features

Character Classes and Quantifiers

public class AdvancedPatterns {
    public static void main(String[] args) {
        String input = "User123 logged in from IP 192.168.1.1 at 14:30";
        
        // Match alphanumeric usernames
        Pattern userPattern = Pattern.compile("[A-Za-z]+\\d+");
        
        // Match IP addresses
        Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
        
        // Match timestamps
        Pattern timePattern = Pattern.compile("\\d{2}:\\d{2}");
        
        Matcher userMatcher = userPattern.matcher(input);
        Matcher ipMatcher = ipPattern.matcher(input);
        Matcher timeMatcher = timePattern.matcher(input);
        
        while(userMatcher.find()) {
            System.out.println("Username: " + userMatcher.group());
        }
        
        while(ipMatcher.find()) {
            System.out.println("IP Address: " + ipMatcher.group());
        }
        
        while(timeMatcher.find()) {
            System.out.println("Timestamp: " + timeMatcher.group());
        }
    }
}

Grouping and Capturing

public class GroupCapture {
    public static void main(String[] args) {
        String logEntry = "DEBUG [main] com.example.App - Processing request ID: ABC123-XYZ456";
        
        // Named capture groups
        Pattern logPattern = Pattern.compile(
            "(?<level>\\w+)\\s\\[(?<thread>\\w+)\\]\\s(?<class>[\\w.]+)\\s-\\s(?<message>.+)"
        );
        
        Matcher logMatcher = logPattern.matcher(logEntry);
        
        if(logMatcher.find()) {
            System.out.println("Log Level: " + logMatcher.group("level"));
            System.out.println("Thread: " + logMatcher.group("thread"));
            System.out.println("Class: " + logMatcher.group("class"));
            System.out.println("Message: " + logMatcher.group("message"));
        }
    }
}

Lookahead and Lookbehind

public class Lookaround {
    public static void main(String[] args) {
        String data = "price: $19.99, discount: 15%, total: $16.99";
        
        // Positive lookbehind for prices
        Pattern pricePattern = Pattern.compile("(?<=\\$)\\d+\\.\\d{2}");
        
        // Positive lookahead for percentages
        Pattern percentPattern = Pattern.compile("\\d+(?=%)");
        
        Matcher priceMatcher = pricePattern.matcher(data);
        Matcher percentMatcher = percentPattern.matcher(data);
        
        while(priceMatcher.find()) {
            System.out.println("Price value: " + priceMatcher.group());
        }
        
        while(percentMatcher.find()) {
            System.out.println("Percentage: " + percentMatcher.group());
        }
    }
}

Tags: regex pattern-matching text-processing java

Posted on Tue, 01 Sep 2026 16:12:24 +0000 by ghostrider1