Real applications need to validate emails, extract phone numbers, parse URLs, and clean text. Reusable regex patterns help solve common validation and extraction tasks while keeping the matching logic explicit.

Email Validation

Email.java
// Email validation patterns

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Email {

    public static void main(String[] args) {
        // Basic email pattern
        String basicEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        
        String[] emails = {
            "user@example.com",
            "first.last@domain.co.uk",
            "user+tag@example.org",
            "invalid@",
            "@invalid.com",
            "no-at-sign.com",
            "user@domain",
            "user@domain.c"
        };

        System.out.println("Basic email validation:");
        Pattern pattern = Pattern.compile(basicEmail);
        for (String email : emails) {
            boolean valid = pattern.matcher(email).matches();
            System.out.println("  " + email + ": " + valid);
        }

        // Extract email parts
        String emailPattern = "^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})$";
        Pattern extractPattern = Pattern.compile(emailPattern);
        
        System.out.println("\nExtract email parts:");
        String testEmail = ;
        Matcher matcher = extractPattern.matcher(testEmail);
        
        if (matcher.matches()) {
            System.out.println("  Email: " + testEmail);
            System.out.println("  Username: " + matcher.group(1));
            System.out.println("  Domain: " + matcher.group(2));
            System.out.println("  TLD: " + matcher.group(3));
        }

        // Find all emails in text
        String text = """
            Contact us at support@example.com or sales@company.org.
            For urgent matters, email admin@service.net immediately.
            """;

        Pattern findPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
        Matcher findMatcher = findPattern.matcher(text);

        System.out.println("\nEmails found in text:");
        while (findMatcher.find()) {
            System.out.println("  " + findMatcher.group());
        }

        // More strict pattern (requires valid TLD length)
        String strictEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
        Pattern strictPattern = Pattern.compile(strictEmail);

        System.out.println("\nStrict validation:");
        String[] testEmails = {
            "user@domain.com",
            "user@domain.co",
            "user@domain.technology"  // 10 chars TLD
        };
        
        for (String email : testEmails) {
            boolean valid = strictPattern.matcher(email).matches();
            System.out.println("  " + email + ": " + valid);
        }
    }

}
// Email validation patterns

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Email {

    public static void main(String[] args) {
        // Basic email pattern
        String basicEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        
        String[] emails = {
            "user@example.com",
            "first.last@domain.co.uk",
            "user+tag@example.org",
            "invalid@",
            "@invalid.com",
            "no-at-sign.com",
            "user@domain",
            "user@domain.c"
        };

        System.out.println("Basic email validation:");
        Pattern pattern = Pattern.compile(basicEmail);
        for (String email : emails) {
            boolean valid = pattern.matcher(email).matches();
            System.out.println("  " + email + ": " + valid);
        }

        // Extract email parts
        String emailPattern = "^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})$";
        Pattern extractPattern = Pattern.compile(emailPattern);
        
        System.out.println("\nExtract email parts:");
        String testEmail = ;
        Matcher matcher = extractPattern.matcher(testEmail);
        
        if (matcher.matches()) {
            System.out.println("  Email: " + testEmail);
            System.out.println("  Username: " + matcher.group(1));
            System.out.println("  Domain: " + matcher.group(2));
            System.out.println("  TLD: " + matcher.group(3));
        }

        // Find all emails in text
        String text = """
            Contact us at support@example.com or sales@company.org.
            For urgent matters, email admin@service.net immediately.
            """;

        Pattern findPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
        Matcher findMatcher = findPattern.matcher(text);

        System.out.println("\nEmails found in text:");
        while (findMatcher.find()) {
            System.out.println("  " + findMatcher.group());
        }

        // More strict pattern (requires valid TLD length)
        String strictEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
        Pattern strictPattern = Pattern.compile(strictEmail);

        System.out.println("\nStrict validation:");
        String[] testEmails = {
            "user@domain.com",
            "user@domain.co",
            "user@domain.technology"  // 10 chars TLD
        };
        
        for (String email : testEmails) {
            boolean valid = strictPattern.matcher(email).matches();
            System.out.println("  " + email + ": " + valid);
        }
    }

}
email_pattern An email pattern matches a local part, an at sign, a domain, and a top-level domain. Production email validation can be stricter than this simplified form.

Phone Number Validation

Phone.java
// Phone number patterns

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Phone {

    public static void main(String[] args) {
        // US phone formats
        String[] patterns = {
            "\\(\\d{3}\\)\\s\\d{3}-\\d{4}",  // (123) 456-7890
            "\\d{3}-\\d{3}-\\d{4}",           // 123-456-7890
            "\\d{10}"                         // 1234567890
        };

        String[] phones = {
            "(555) 123-4567",
            "555-123-4567",
            "5551234567",
            "(555)123-4567",  // no space
            "555.123.4567",
            "invalid"
        };

        System.out.println("Phone validation:");
        for (int i = 0; i < patterns.length; i++) {
            System.out.println("\nPattern " + (i+1) + ":");
            Pattern p = Pattern.compile(patterns[i]);
            for (String phone : phones) {
                boolean valid = p.matcher(phone).matches();
                System.out.println("  " + phone + ": " + valid);
            }
        }

        // Combined pattern (any format)
        String anyFormat = "^(\\(\\d{3}\\)\\s?|\\d{3}-)?\\d{3}-?\\d{4}$";
        Pattern anyPattern = Pattern.compile(anyFormat);

        System.out.println("\nCombined pattern:");
        for (String phone : phones) {
            boolean valid = anyPattern.matcher(phone).matches();
            System.out.println("  " + phone + ": " + valid);
        }

        // Extract phone parts
        String extractPattern = "\\((\\d{3})\\)\\s(\\d{3})-(\\d{4})";
        Pattern extract = Pattern.compile(extractPattern);
        
        String testPhone = ;
        Matcher matcher = extract.matcher(testPhone);

        if (matcher.matches()) {
            System.out.println("\nExtracted parts from " + testPhone + ":");
            System.out.println("  Area code: " + matcher.group(1));
            System.out.println("  Exchange: " + matcher.group(2));
            System.out.println("  Number: " + matcher.group(3));
        }

        // Find all phones in text
        String text = """
            Call us at (555) 123-4567 or 555-987-6543.
            Emergency: (999) 911-0000
            """;

        Pattern findPattern = Pattern.compile("\\(?\\d{3}\\)?[-\\s]?\\d{3}-\\d{4}");
        Matcher findMatcher = findPattern.matcher(text);

        System.out.println("\nPhones found in text:");
        while (findMatcher.find()) {
            System.out.println("  " + findMatcher.group());
        }

        // International format (basic)
        String intlPattern = "^\\+?\\d{1,3}[-\\s]?\\(?\\d{1,4}\\)?[-\\s]?\\d{1,4}[-\\s]?\\d{1,9}$";
        Pattern intlP = Pattern.compile(intlPattern);

        String[] intlPhones = {
            "+1 (555) 123-4567",
            "+44 20 7123 4567",
            "+81 3-1234-5678"
        };

        System.out.println("\nInternational phones:");
        for (String phone : intlPhones) {
            boolean valid = intlP.matcher(phone).matches();
            System.out.println("  " + phone + ": " + valid);
        }
    }

}
// Phone number patterns

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Phone {

    public static void main(String[] args) {
        // US phone formats
        String[] patterns = {
            "\\(\\d{3}\\)\\s\\d{3}-\\d{4}",  // (123) 456-7890
            "\\d{3}-\\d{3}-\\d{4}",           // 123-456-7890
            "\\d{10}"                         // 1234567890
        };

        String[] phones = {
            "(555) 123-4567",
            "555-123-4567",
            "5551234567",
            "(555)123-4567",  // no space
            "555.123.4567",
            "invalid"
        };

        System.out.println("Phone validation:");
        for (int i = 0; i < patterns.length; i++) {
            System.out.println("\nPattern " + (i+1) + ":");
            Pattern p = Pattern.compile(patterns[i]);
            for (String phone : phones) {
                boolean valid = p.matcher(phone).matches();
                System.out.println("  " + phone + ": " + valid);
            }
        }

        // Combined pattern (any format)
        String anyFormat = "^(\\(\\d{3}\\)\\s?|\\d{3}-)?\\d{3}-?\\d{4}$";
        Pattern anyPattern = Pattern.compile(anyFormat);

        System.out.println("\nCombined pattern:");
        for (String phone : phones) {
            boolean valid = anyPattern.matcher(phone).matches();
            System.out.println("  " + phone + ": " + valid);
        }

        // Extract phone parts
        String extractPattern = "\\((\\d{3})\\)\\s(\\d{3})-(\\d{4})";
        Pattern extract = Pattern.compile(extractPattern);
        
        String testPhone = ;
        Matcher matcher = extract.matcher(testPhone);

        if (matcher.matches()) {
            System.out.println("\nExtracted parts from " + testPhone + ":");
            System.out.println("  Area code: " + matcher.group(1));
            System.out.println("  Exchange: " + matcher.group(2));
            System.out.println("  Number: " + matcher.group(3));
        }

        // Find all phones in text
        String text = """
            Call us at (555) 123-4567 or 555-987-6543.
            Emergency: (999) 911-0000
            """;

        Pattern findPattern = Pattern.compile("\\(?\\d{3}\\)?[-\\s]?\\d{3}-\\d{4}");
        Matcher findMatcher = findPattern.matcher(text);

        System.out.println("\nPhones found in text:");
        while (findMatcher.find()) {
            System.out.println("  " + findMatcher.group());
        }

        // International format (basic)
        String intlPattern = "^\\+?\\d{1,3}[-\\s]?\\(?\\d{1,4}\\)?[-\\s]?\\d{1,4}[-\\s]?\\d{1,9}$";
        Pattern intlP = Pattern.compile(intlPattern);

        String[] intlPhones = {
            "+1 (555) 123-4567",
            "+44 20 7123 4567",
            "+81 3-1234-5678"
        };

        System.out.println("\nInternational phones:");
        for (String phone : intlPhones) {
            boolean valid = intlP.matcher(phone).matches();
            System.out.println("  " + phone + ": " + valid);
        }
    }

}
phone_pattern A phone pattern can match common formats such as parenthesized area codes, hyphen-separated numbers, and compact digit-only values.

URL Validation

Url.java
// URL patterns

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Url {

    public static void main(String[] args) {
        // Basic URL pattern
        String urlPattern = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$";
        
        String[] urls = {
            "https://example.com",
            "http://www.example.com",
            "https://sub.example.co.uk",
            "https://example.com/path",
            "https://example.com/path?key=value",
            "ftp://example.com",  // wrong protocol
            "example.com",        // missing protocol
            "https://localhost"   // no TLD
        };

        System.out.println("URL validation:");
        Pattern pattern = Pattern.compile(urlPattern);
        for (String url : urls) {
            boolean valid = pattern.matcher(url).matches();
            System.out.println("  " + url + ": " + valid);
        }

        // Extract URL parts
        String extractPattern = "^(https?)://([a-zA-Z0-9.-]+)(/.*)?$";
        Pattern extractP = Pattern.compile(extractPattern);

        String testUrl = ;
        Matcher matcher = extractP.matcher(testUrl);

        if (matcher.matches()) {
            System.out.println("\nExtracted parts from " + testUrl + ":");
            System.out.println("  Protocol: " + matcher.group(1));
            System.out.println("  Domain: " + matcher.group(2));
            System.out.println("  Path: " + (matcher.group(3) != null ? matcher.group(3) : "/"));
        }

        // More detailed extraction
        String detailPattern = "^(https?)://([^:/]+)(:(\\d+))?(/.*)?$";
        Pattern detailP = Pattern.compile(detailPattern);

        String[] testUrls = {
            "https://example.com:8080/path",
            "http://localhost:3000/api",
            "https://example.com/page"
        };

        System.out.println("\nDetailed URL parsing:");
        for (String url : testUrls) {
            Matcher m = detailP.matcher(url);
            if (m.matches()) {
                System.out.println("  " + url);
                System.out.println("    Protocol: " + m.group(1));
                System.out.println("    Host: " + m.group(2));
                System.out.println("    Port: " + (m.group(4) != null ? m.group(4) : "default"));
                System.out.println("    Path: " + (m.group(5) != null ? m.group(5) : "/"));
            }
        }

        // Find all URLs in text
        String text = """
            Visit https://example.com for more info.
            Check out http://test.org/page and https://another.site/path?q=search
            """;

        Pattern findPattern = Pattern.compile("https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}[^\\s]*");
        Matcher findMatcher = findPattern.matcher(text);

        System.out.println("\nURLs found in text:");
        while (findMatcher.find()) {
            System.out.println("  " + findMatcher.group());
        }

        // Query parameters
        String queryPattern = "[?&]([^=]+)=([^&]+)";
        String urlWithQuery = "https://example.com/search?q=regex&lang=java&page=1";
        
        Pattern queryP = Pattern.compile(queryPattern);
        Matcher queryM = queryP.matcher(urlWithQuery);

        System.out.println("\nQuery parameters from: " + urlWithQuery);
        while (queryM.find()) {
            System.out.println("  " + queryM.group(1) + " = " + queryM.group(2));
        }
    }

}
// URL patterns

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Url {

    public static void main(String[] args) {
        // Basic URL pattern
        String urlPattern = "^https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}.*$";
        
        String[] urls = {
            "https://example.com",
            "http://www.example.com",
            "https://sub.example.co.uk",
            "https://example.com/path",
            "https://example.com/path?key=value",
            "ftp://example.com",  // wrong protocol
            "example.com",        // missing protocol
            "https://localhost"   // no TLD
        };

        System.out.println("URL validation:");
        Pattern pattern = Pattern.compile(urlPattern);
        for (String url : urls) {
            boolean valid = pattern.matcher(url).matches();
            System.out.println("  " + url + ": " + valid);
        }

        // Extract URL parts
        String extractPattern = "^(https?)://([a-zA-Z0-9.-]+)(/.*)?$";
        Pattern extractP = Pattern.compile(extractPattern);

        String testUrl = ;
        Matcher matcher = extractP.matcher(testUrl);

        if (matcher.matches()) {
            System.out.println("\nExtracted parts from " + testUrl + ":");
            System.out.println("  Protocol: " + matcher.group(1));
            System.out.println("  Domain: " + matcher.group(2));
            System.out.println("  Path: " + (matcher.group(3) != null ? matcher.group(3) : "/"));
        }

        // More detailed extraction
        String detailPattern = "^(https?)://([^:/]+)(:(\\d+))?(/.*)?$";
        Pattern detailP = Pattern.compile(detailPattern);

        String[] testUrls = {
            "https://example.com:8080/path",
            "http://localhost:3000/api",
            "https://example.com/page"
        };

        System.out.println("\nDetailed URL parsing:");
        for (String url : testUrls) {
            Matcher m = detailP.matcher(url);
            if (m.matches()) {
                System.out.println("  " + url);
                System.out.println("    Protocol: " + m.group(1));
                System.out.println("    Host: " + m.group(2));
                System.out.println("    Port: " + (m.group(4) != null ? m.group(4) : "default"));
                System.out.println("    Path: " + (m.group(5) != null ? m.group(5) : "/"));
            }
        }

        // Find all URLs in text
        String text = """
            Visit https://example.com for more info.
            Check out http://test.org/page and https://another.site/path?q=search
            """;

        Pattern findPattern = Pattern.compile("https?://[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}[^\\s]*");
        Matcher findMatcher = findPattern.matcher(text);

        System.out.println("\nURLs found in text:");
        while (findMatcher.find()) {
            System.out.println("  " + findMatcher.group());
        }

        // Query parameters
        String queryPattern = "[?&]([^=]+)=([^&]+)";
        String urlWithQuery = "https://example.com/search?q=regex&lang=java&page=1";
        
        Pattern queryP = Pattern.compile(queryPattern);
        Matcher queryM = queryP.matcher(urlWithQuery);

        System.out.println("\nQuery parameters from: " + urlWithQuery);
        while (queryM.find()) {
            System.out.println("  " + queryM.group(1) + " = " + queryM.group(2));
        }
    }

}
url_pattern A URL pattern can capture a protocol, host, optional port, path, and query string.

Extraction Operations

Extraction.java
// Text extraction with regex

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;

public class Extraction {

    public static List<String> extractHashtags(String text) {
        List<String> hashtags = new ArrayList<>();
        Pattern pattern = Pattern.compile("#\\w+");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            hashtags.add(matcher.group());
        }
        return hashtags;
    }

    public static List<String> extractMentions(String text) {
        List<String> mentions = new ArrayList<>();
        Pattern pattern = Pattern.compile("@\\w+");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            mentions.add(matcher.group());
        }
        return mentions;
    }

    public static List<Double> extractNumbers(String text) {
        List<Double> numbers = new ArrayList<>();
        Pattern pattern = Pattern.compile("-?\\d+\\.?\\d*");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            numbers.add(Double.parseDouble(matcher.group()));
        }
        return numbers;
    }

    public static List<String> extractDates(String text) {
        List<String> dates = new ArrayList<>();
        // YYYY-MM-DD format
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            dates.add(matcher.group());
        }
        return dates;
    }

    public static void main(String[] args) {
        // Social media text
        String tweet = """
            Loving #java and #regex! Thanks @copilot for the help.
            Check out #programming tips at https://example.com
            Mentions: @user1 @user2 #coding
            """;

        System.out.println("Social media extraction:");
        System.out.println("Hashtags: " + extractHashtags(tweet));
        System.out.println("Mentions: " + extractMentions(tweet));

        // Numbers
        String dataText = "Prices: $19.99, $5.50, and $100. Temperature: -5.5°C";
        System.out.println("\nNumbers extraction:");
        System.out.println("Numbers: " + extractNumbers(dataText));

        // Dates
        String logText = """
            2025-01-29: Error occurred
            2025-01-30: Fixed bug
            2025-02-01: Deployed
            """;
        System.out.println("\nDates extraction:");
        System.out.println("Dates: " + extractDates(logText));

        // IP addresses
        String serverLog = "Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10";
        Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
        Matcher ipMatcher = ipPattern.matcher(serverLog);

        System.out.println("\nIP addresses:");
        while (ipMatcher.find()) {
            System.out.println("  " + ipMatcher.group());
        }

        // Extract quoted strings
        String quoteText = "He said \"Hello\" and she replied \"Hi there!\"";
        Pattern quotePattern = Pattern.compile("\"([^\"]+)\"");
        Matcher quoteMatcher = quotePattern.matcher(quoteText);

        System.out.println("\nQuoted strings:");
        while (quoteMatcher.find()) {
            System.out.println("  " + quoteMatcher.group(1));
        }

        // Key-value pairs
        String config = ;
        Pattern kvPattern = Pattern.compile("(\\w+)=(\\S+)");
        Matcher kvMatcher = kvPattern.matcher(config);

        System.out.println("\nKey-value pairs:");
        while (kvMatcher.find()) {
            System.out.println("  " + kvMatcher.group(1) + " = " + kvMatcher.group(2));
        }

        // HTML tags (simple)
        String html = "<div>Content</div><span>Text</span>";
        Pattern tagPattern = Pattern.compile("<(\\w+)>([^<]+)</\\1>");
        Matcher tagMatcher = tagPattern.matcher(html);

        System.out.println("\nHTML content:");
        while (tagMatcher.find()) {
            System.out.println("  <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));
        }
    }

}
// Text extraction with regex

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;

public class Extraction {

    public static List<String> extractHashtags(String text) {
        List<String> hashtags = new ArrayList<>();
        Pattern pattern = Pattern.compile("#\\w+");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            hashtags.add(matcher.group());
        }
        return hashtags;
    }

    public static List<String> extractMentions(String text) {
        List<String> mentions = new ArrayList<>();
        Pattern pattern = Pattern.compile("@\\w+");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            mentions.add(matcher.group());
        }
        return mentions;
    }

    public static List<Double> extractNumbers(String text) {
        List<Double> numbers = new ArrayList<>();
        Pattern pattern = Pattern.compile("-?\\d+\\.?\\d*");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            numbers.add(Double.parseDouble(matcher.group()));
        }
        return numbers;
    }

    public static List<String> extractDates(String text) {
        List<String> dates = new ArrayList<>();
        // YYYY-MM-DD format
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            dates.add(matcher.group());
        }
        return dates;
    }

    public static void main(String[] args) {
        // Social media text
        String tweet = """
            Loving #java and #regex! Thanks @copilot for the help.
            Check out #programming tips at https://example.com
            Mentions: @user1 @user2 #coding
            """;

        System.out.println("Social media extraction:");
        System.out.println("Hashtags: " + extractHashtags(tweet));
        System.out.println("Mentions: " + extractMentions(tweet));

        // Numbers
        String dataText = "Prices: $19.99, $5.50, and $100. Temperature: -5.5°C";
        System.out.println("\nNumbers extraction:");
        System.out.println("Numbers: " + extractNumbers(dataText));

        // Dates
        String logText = """
            2025-01-29: Error occurred
            2025-01-30: Fixed bug
            2025-02-01: Deployed
            """;
        System.out.println("\nDates extraction:");
        System.out.println("Dates: " + extractDates(logText));

        // IP addresses
        String serverLog = "Requests from 192.168.1.1, 10.0.0.5, and 172.16.0.10";
        Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
        Matcher ipMatcher = ipPattern.matcher(serverLog);

        System.out.println("\nIP addresses:");
        while (ipMatcher.find()) {
            System.out.println("  " + ipMatcher.group());
        }

        // Extract quoted strings
        String quoteText = "He said \"Hello\" and she replied \"Hi there!\"";
        Pattern quotePattern = Pattern.compile("\"([^\"]+)\"");
        Matcher quoteMatcher = quotePattern.matcher(quoteText);

        System.out.println("\nQuoted strings:");
        while (quoteMatcher.find()) {
            System.out.println("  " + quoteMatcher.group(1));
        }

        // Key-value pairs
        String config = ;
        Pattern kvPattern = Pattern.compile("(\\w+)=(\\S+)");
        Matcher kvMatcher = kvPattern.matcher(config);

        System.out.println("\nKey-value pairs:");
        while (kvMatcher.find()) {
            System.out.println("  " + kvMatcher.group(1) + " = " + kvMatcher.group(2));
        }

        // HTML tags (simple)
        String html = "<div>Content</div><span>Text</span>";
        Pattern tagPattern = Pattern.compile("<(\\w+)>([^<]+)</\\1>");
        Matcher tagMatcher = tagPattern.matcher(html);

        System.out.println("\nHTML content:");
        while (tagMatcher.find()) {
            System.out.println("  <" + tagMatcher.group(1) + ">: " + tagMatcher.group(2));
        }
    }

}
extraction Capturing groups and repeated find calls pull pieces of information out of larger text.

Splitting Text

split uses a regex delimiter, so it can split on whitespace, punctuation, repeated separators, or a compiled pattern.

Splitting.java
// String splitting with regex

import java.util.Arrays;
import java.util.regex.Pattern;

public class Splitting {

    public static void main(String[] args) {
        // Split by comma
        String csv1 = ;
        String[] parts1 = csv1.split(",");
        System.out.println("Split by comma:");
        System.out.println("  " + Arrays.toString(parts1));

        // Split by whitespace
        String text1 = "one two  three   four";
        String[] parts2 = text1.split("\\s+");
        System.out.println("\nSplit by whitespace:");
        System.out.println("  " + Arrays.toString(parts2));

        // Split by multiple delimiters
        String text2 = "apple;banana,cherry:orange";
        String[] parts3 = text2.split("[;,:]+");
        System.out.println("\nSplit by multiple delimiters:");
        System.out.println("  " + Arrays.toString(parts3));

        // Split with limit
        String text3 = "one,two,three,four,five";
        String[] parts4 = text3.split(",", 3);
        System.out.println("\nSplit with limit (3):");
        System.out.println("  " + Arrays.toString(parts4));

        // Split preserving delimiters (lookahead)
        String text4 = "one,two,three";
        String[] parts5 = text4.split("(?=,)");
        System.out.println("\nSplit preserving delimiters:");
        System.out.println("  " + Arrays.toString(parts5));

        // Split by word boundaries
        String text5 = "hello-world_test";
        String[] parts6 = text5.split("[-_]");
        System.out.println("\nSplit by hyphens and underscores:");
        System.out.println("  " + Arrays.toString(parts6));

        // Split sentences
        String paragraph = "First sentence. Second sentence! Third question?";
        String[] sentences = paragraph.split("[.!?]\\s*");
        System.out.println("\nSplit sentences:");
        for (int i = 0; i < sentences.length; i++) {
            System.out.println("  " + (i+1) + ": " + sentences[i]);
        }

        // Split keeping empty strings
        String text6 = "a,,b,,,c";
        String[] parts7 = text6.split(",");
        String[] parts8 = text6.split(",", -1);
        System.out.println("\nDefault (discard trailing empty):");
        System.out.println("  " + Arrays.toString(parts7));
        System.out.println("Keep empty strings (limit = -1):");
        System.out.println("  " + Arrays.toString(parts8));

        // Split path
        String path = "C:\\Users\\John\\Documents\\file.txt";
        String[] pathParts = path.split("\\\\");
        System.out.println("\nSplit Windows path:");
        System.out.println("  " + Arrays.toString(pathParts));

        // Split by digits
        String text7 = "abc123def456ghi";
        String[] parts9 = text7.split("\\d+");
        System.out.println("\nSplit by digits:");
        System.out.println("  " + Arrays.toString(parts9));

        // Compiled pattern for reuse
        Pattern pattern = Pattern.compile("\\s*,\\s*");  // comma with optional spaces
        String text8 = "a, b,c ,d , e";
        String[] parts10 = pattern.split(text8);
        System.out.println("\nSplit CSV with spaces:");
        System.out.println("  " + Arrays.toString(parts10));

        // Split complex: key=value pairs
        String config = "name=John;age=30;city=NYC";
        String[] pairs = config.split(";");
        System.out.println("\nParse config:");
        for (String pair : pairs) {
            String[] kv = pair.split("=");
            System.out.println("  " + kv[0] + " -> " + kv[1]);
        }
    }

}
// String splitting with regex

import java.util.Arrays;
import java.util.regex.Pattern;

public class Splitting {

    public static void main(String[] args) {
        // Split by comma
        String csv1 = ;
        String[] parts1 = csv1.split(",");
        System.out.println("Split by comma:");
        System.out.println("  " + Arrays.toString(parts1));

        // Split by whitespace
        String text1 = "one two  three   four";
        String[] parts2 = text1.split("\\s+");
        System.out.println("\nSplit by whitespace:");
        System.out.println("  " + Arrays.toString(parts2));

        // Split by multiple delimiters
        String text2 = "apple;banana,cherry:orange";
        String[] parts3 = text2.split("[;,:]+");
        System.out.println("\nSplit by multiple delimiters:");
        System.out.println("  " + Arrays.toString(parts3));

        // Split with limit
        String text3 = "one,two,three,four,five";
        String[] parts4 = text3.split(",", 3);
        System.out.println("\nSplit with limit (3):");
        System.out.println("  " + Arrays.toString(parts4));

        // Split preserving delimiters (lookahead)
        String text4 = "one,two,three";
        String[] parts5 = text4.split("(?=,)");
        System.out.println("\nSplit preserving delimiters:");
        System.out.println("  " + Arrays.toString(parts5));

        // Split by word boundaries
        String text5 = "hello-world_test";
        String[] parts6 = text5.split("[-_]");
        System.out.println("\nSplit by hyphens and underscores:");
        System.out.println("  " + Arrays.toString(parts6));

        // Split sentences
        String paragraph = "First sentence. Second sentence! Third question?";
        String[] sentences = paragraph.split("[.!?]\\s*");
        System.out.println("\nSplit sentences:");
        for (int i = 0; i < sentences.length; i++) {
            System.out.println("  " + (i+1) + ": " + sentences[i]);
        }

        // Split keeping empty strings
        String text6 = "a,,b,,,c";
        String[] parts7 = text6.split(",");
        String[] parts8 = text6.split(",", -1);
        System.out.println("\nDefault (discard trailing empty):");
        System.out.println("  " + Arrays.toString(parts7));
        System.out.println("Keep empty strings (limit = -1):");
        System.out.println("  " + Arrays.toString(parts8));

        // Split path
        String path = "C:\\Users\\John\\Documents\\file.txt";
        String[] pathParts = path.split("\\\\");
        System.out.println("\nSplit Windows path:");
        System.out.println("  " + Arrays.toString(pathParts));

        // Split by digits
        String text7 = "abc123def456ghi";
        String[] parts9 = text7.split("\\d+");
        System.out.println("\nSplit by digits:");
        System.out.println("  " + Arrays.toString(parts9));

        // Compiled pattern for reuse
        Pattern pattern = Pattern.compile("\\s*,\\s*");  // comma with optional spaces
        String text8 = "a, b,c ,d , e";
        String[] parts10 = pattern.split(text8);
        System.out.println("\nSplit CSV with spaces:");
        System.out.println("  " + Arrays.toString(parts10));

        // Split complex: key=value pairs
        String config = "name=John;age=30;city=NYC";
        String[] pairs = config.split(";");
        System.out.println("\nParse config:");
        for (String pair : pairs) {
            String[] kv = pair.split("=");
            System.out.println("  " + kv[0] + " -> " + kv[1]);
        }
    }

}

Replacement

replaceAll and Matcher replacement methods use regex matches to clean, mask, or reformat text.

Replacement.java
// String replacement with regex

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Replacement {

    public static void main(String[] args) {
        // Simple replaceAll
        String text1 = "Hello World, Hello Java";
        String result1 = text1.replaceAll("Hello", "Hi");
        System.out.println("Original: " + text1);
        System.out.println("Replaced: " + result1);

        // Replace with pattern
        String text2 = "Call 555-1234 or 555-5678";
        String result2 = text2.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");
        System.out.println("\nMask phone numbers:");
        System.out.println("Original: " + text2);
        System.out.println("Masked: " + result2);

        // Replace with groups
        String text3 = "2025-01-29";
        String result3 = text3.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
        System.out.println("\nReformat date:");
        System.out.println("Original (YYYY-MM-DD): " + text3);
        System.out.println("Reformatted (MM/DD/YYYY): " + result3);

        // Remove extra whitespace
        String text4 = "Too    many     spaces";
        String result4 = text4.replaceAll("\\s+", " ");
        System.out.println("\nNormalize whitespace:");
        System.out.println("Original: '" + text4 + "'");
        System.out.println("Normalized: '" + result4 + "'");

        // Remove HTML tags
        String html = "<p>Hello <b>World</b></p>";
        String result5 = html.replaceAll("<[^>]+>", "");
        System.out.println("\nRemove HTML:");
        System.out.println("Original: " + html);
        System.out.println("Clean: " + result5);

        // Censor profanity (example)
        String text6 = ;
        String result6 = text6.replaceAll("\\b(bad|terrible)\\b", "***");
        System.out.println("\nCensor words:");
        System.out.println("Original: " + text6);
        System.out.println("Censored: " + result6);

        // Format currency
        String text7 = "Price: 1234.56";
        String result7 = text7.replaceAll("(\\d+)", "\\$$1");
        System.out.println("\nAdd currency:");
        System.out.println("Original: " + text7);
        System.out.println("Formatted: " + result7);

        // Matcher with appendReplacement (more control)
        String text8 = "one two three";
        Pattern pattern = Pattern.compile("(\\w+)");
        Matcher matcher = pattern.matcher(text8);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String word = matcher.group(1);
            matcher.appendReplacement(result, word.toUpperCase());
        }
        matcher.appendTail(result);

        System.out.println("\nCustom replacement:");
        System.out.println("Original: " + text8);
        System.out.println("Uppercase: " + result);

        // Advanced: swap first and last name
        String names = "John Doe, Jane Smith, Bob Johnson";
        String result9 = names.replaceAll("(\\w+)\\s(\\w+)", "$2, $1");
        System.out.println("\nSwap names:");
        System.out.println("Original: " + names);
        System.out.println("Swapped: " + result9);
    }

}
// String replacement with regex

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Replacement {

    public static void main(String[] args) {
        // Simple replaceAll
        String text1 = "Hello World, Hello Java";
        String result1 = text1.replaceAll("Hello", "Hi");
        System.out.println("Original: " + text1);
        System.out.println("Replaced: " + result1);

        // Replace with pattern
        String text2 = "Call 555-1234 or 555-5678";
        String result2 = text2.replaceAll("\\d{3}-\\d{4}", "XXX-XXXX");
        System.out.println("\nMask phone numbers:");
        System.out.println("Original: " + text2);
        System.out.println("Masked: " + result2);

        // Replace with groups
        String text3 = "2025-01-29";
        String result3 = text3.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
        System.out.println("\nReformat date:");
        System.out.println("Original (YYYY-MM-DD): " + text3);
        System.out.println("Reformatted (MM/DD/YYYY): " + result3);

        // Remove extra whitespace
        String text4 = "Too    many     spaces";
        String result4 = text4.replaceAll("\\s+", " ");
        System.out.println("\nNormalize whitespace:");
        System.out.println("Original: '" + text4 + "'");
        System.out.println("Normalized: '" + result4 + "'");

        // Remove HTML tags
        String html = "<p>Hello <b>World</b></p>";
        String result5 = html.replaceAll("<[^>]+>", "");
        System.out.println("\nRemove HTML:");
        System.out.println("Original: " + html);
        System.out.println("Clean: " + result5);

        // Censor profanity (example)
        String text6 = ;
        String result6 = text6.replaceAll("\\b(bad|terrible)\\b", "***");
        System.out.println("\nCensor words:");
        System.out.println("Original: " + text6);
        System.out.println("Censored: " + result6);

        // Format currency
        String text7 = "Price: 1234.56";
        String result7 = text7.replaceAll("(\\d+)", "\\$$1");
        System.out.println("\nAdd currency:");
        System.out.println("Original: " + text7);
        System.out.println("Formatted: " + result7);

        // Matcher with appendReplacement (more control)
        String text8 = "one two three";
        Pattern pattern = Pattern.compile("(\\w+)");
        Matcher matcher = pattern.matcher(text8);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String word = matcher.group(1);
            matcher.appendReplacement(result, word.toUpperCase());
        }
        matcher.appendTail(result);

        System.out.println("\nCustom replacement:");
        System.out.println("Original: " + text8);
        System.out.println("Uppercase: " + result);

        // Advanced: swap first and last name
        String names = "John Doe, Jane Smith, Bob Johnson";
        String result9 = names.replaceAll("(\\w+)\\s(\\w+)", "$2, $1");
        System.out.println("\nSwap names:");
        System.out.println("Original: " + names);
        System.out.println("Swapped: " + result9);
    }

}

Exercise: Practical.java

Extract all hashtags and mentions from a social media post and return them as separate lists