← Back to Home

Module 2: Intro to RegEx

Module Overview

Learn about Regular Expressions (RegEx) in Java and how to use them for pattern matching, validation, and text processing. Regular expressions provide a powerful way to search, extract, and manipulate text based on patterns.

Learning Objectives

RegEx Fundamentals

Regular expressions (RegEx) are sequences of characters that define a search pattern. They are used for pattern matching within text and are supported in most programming languages, including Java.

Common RegEx Patterns

Here are some common patterns used in regular expressions:

Capture Groups

Capture groups allow you to extract parts of the matched text:

Example Implementation

Here's how you might use RegEx in Java for various common tasks:

// Simple pattern matching
String text = "Java Regular Expressions";
boolean matches = text.matches(".*Regular.*"); // true

// Finding all matches in a string
String text = "Contact us at support@example.com or sales@example.com";
Pattern pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {
    System.out.println("Found email: " + matcher.group());
}

// Using capture groups to extract data
String dateString = "Today is 2023-05-15";
Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher matcher = pattern.matcher(dateString);

if (matcher.find()) {
    String year = matcher.group(1);  // 2023
    String month = matcher.group(2); // 05
    String day = matcher.group(3);   // 15
    System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day);
}

// Using named capture groups
String nameString = "John Doe";
Pattern pattern = Pattern.compile("(?<firstName>\\w+)\\s(?<lastName>\\w+)");
Matcher matcher = pattern.matcher(nameString);

if (matcher.find()) {
    String firstName = matcher.group("firstName"); // John
    String lastName = matcher.group("lastName");   // Doe
    System.out.println("First name: " + firstName + ", Last name: " + lastName);
}

Resources