Regex Pattern Matching and Extraction

Uses Pattern and Matcher classes to validate email addresses, extract groups, replace text, and split strings with regular expressions.

JavaForm Validation

Code

javasnippet
37 lines
import java.util.regex.*;
import java.util.List;

public class RegexPatternMatching {

    static boolean isValidEmail(String email) {
        Pattern pattern = Pattern.compile(
            "^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$"
        );
        return pattern.matcher(email).matches();
    }

    public static void main(String[] args) {
        List<String> emails = List.of(
            "user@example.com",
            "invalid-email",
            "test.user@domain.org"
        );

        for (String email : emails) {
            System.out.println(email + " -> " + isValidEmail(email));
        }

        String text = "Order #12345 confirmed on 2025-01-15";
        Pattern orderPattern = Pattern.compile("Order #(\\d+)");
        Matcher matcher = orderPattern.matcher(text);
        if (matcher.find()) {
            System.out.println("Order ID: " + matcher.group(1));
        }

        String cleaned = text.replaceAll("\\d", "*");
        System.out.println("Masked: " + cleaned);

        String[] parts = "a,b,,c".split(",");
        System.out.println("Parts: " + parts.length);
    }
}

How it works

Regex Pattern Matching and Extraction keeps everything in the class RegexPatternMatching and the functions isValidEmail and main.

A single loop drives the file — for (String email : emails).

Applying it

Entry signature: static boolean isValidEmail(String email)

Running the file prints labeled results such as Order ID:, Masked:, Parts: — each operation’s effect is visible in the output.

Start the program and main runs isValidEmail one after another.

Statements that matter

return pattern.matcher(email).matches();

Interactive Tools for This Topic

FAQ

What does Regex Pattern Matching and Extraction print when run?
Execute the whole file; each printed line is prefixed with a label like `Order ID:`, `Masked:`, `Parts:`.