SrcForge

Lesson 18

Regex (Regular Expressions)

Java Regex is a powerful API for pattern matching, searching, validating and manipulating strings using the java.util.regex package.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Java Regex defines patterns to search, match, validate and replace text. Commonly used for email validation, password checks, phone matching and data extraction.

Definition List

  • Regular Expression (Regex): A sequence of characters that defines a search pattern.
  • Pattern: A compiled representation of a regular expression.
  • Matcher: An object that performs matching operations on text using a pattern.
  • Capturing Group: A regex part in parentheses () used to extract specific matched text.
  • Metacharacter: A special character with predefined meaning in regular expressions.

Java Regex Package

Java provides regular expression support through the java.util.regex package.

import java.util.regex.*;

Regex Character Classes

  • [abc] — Matches a, b, or c
  • [^abc] — Matches any character except a, b, or c
  • [a-zA-Z] — Matches any uppercase or lowercase letter
  • [a-d[m-p]] — Matches a–d or m–p
  • [a-z&&[def]] — Matches d, e, or f
  • [a-z&&[^bc]] — Matches a–z except b and c
  • [a-z&&[^m-p]] — Matches a–z except m–p

Regex Quantifiers

  • X? — X occurs once or not at all
  • X+ — X occurs one or more times
  • X* — X occurs zero or more times
  • X{n} — X occurs exactly n times
  • X{n,} — X occurs n or more times
  • X{y,z} — X occurs between y and z times

Regex Metacharacters

  • . — Any character
  • \d — Any digit (0–9)
  • \D — Any non-digit
  • \s — Any whitespace character
  • \S — Any non-whitespace character
  • \w — Any word character
  • \W — Any non-word character
  • \b — Word boundary
  • \B — Non-word boundary

Pattern and Matcher Classes

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);

Example 1: Phone Number Matching

package String;

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

public class RegexExample {
    public static void main(String[] args) {
        String inputText = "John: 123-456-7890, Jane: 987-654-3210, Bob: 555-1234";

        String phoneRegex = "\b\d{3}-\d{3}-\d{4}\b";
        Pattern phonePattern = Pattern.compile(phoneRegex);
        Matcher matcher = phonePattern.matcher(inputText);

        System.out.println("Matching phone numbers:");
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

        String areaCodeRegex = "\b(\d{3})-\d{3}-\d{4}\b";
        Pattern areaCodePattern = Pattern.compile(areaCodeRegex);
        Matcher areaCodeMatcher = areaCodePattern.matcher(inputText);

        System.out.println("
Extracted area codes:");
        while (areaCodeMatcher.find()) {
            System.out.println("Area Code: " + areaCodeMatcher.group(1));
        }
    }
}

Example 2: Character Classes and Quantifiers

package String;

import java.util.regex.*;

public class RegexExample2 {
    public static void main(String[] args) {
        Pattern pat = Pattern.compile(" .m");
        Matcher mat = pat.matcher(" .am");
        Boolean bool = mat.matches();
        System.out.println(bool);

        Boolean bool1 = Pattern.matches(" .m", " .am");
        System.out.println(bool1);

        System.out.println(Pattern.matches("[amn]", "acd"));
        System.out.println(Pattern.matches("[^amn]", "c"));
        System.out.println(Pattern.matches("[a-zA-S]", "T"));
        System.out.println(Pattern.matches("[MS][a-z]{5}", "Monica"));
        System.out.println(Pattern.matches("[xyz]?", "x"));
        System.out.println(Pattern.matches("[xyz]+", "x"));
        System.out.println(Pattern.matches("[xyz]*", "xyyza"));
        System.out.println(Pattern.matches("[\d]", "1"));
        System.out.println(Pattern.matches("[\D]", "1"));
    }
}

Common Regex Patterns

  • Email: ^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$
  • Password: ^(?=.*[A-Z])(?=.*[0-9]).{8,}$
  • Phone: ^\d{3}-\d{3}-\d{4}$
  • ZIP Code: ^\d{5}$

FAQ

1. What is Java Regex used for?

Searching, validating, matching, extracting and replacing text patterns in strings.

2. What is the difference between Pattern and Matcher?

Pattern defines the regular expression. Matcher performs matching on text using that pattern.

3. What are regex quantifiers?

Quantifiers specify how many times a character or group can occur in a string.

Java Regex uses the java.util.regex package.
Pattern compiles the regex. Matcher applies it.
Character classes define sets of matchable characters.
Quantifiers control how many times patterns repeat.
Capturing groups extract specific parts of matched text.
Use Pattern.compile() when reusing the same regex.
Regex validates emails, passwords, phones and ZIP codes.

Where Java is used

Java in real-world development

Pattern Class

Compiles a regex into a reusable object. Use Pattern.compile(regex) before matching.

Matcher Class

Applies a pattern to a string. Use find(), group() and matches() for operations.

Character Classes

Define sets of characters to match. Example: [a-zA-Z] matches any letter.

Quantifiers

Control repetition. X? is optional, X+ is one or more, X* is zero or more.

Metacharacters

Shortcuts for common groups. \d matches digits, \w matches word characters.

Capturing Groups

Parentheses () extract specific parts. Use group(1) to get the first captured value.