Regular Expressions

Powerful Pattern Matching for Strings

CPCS203 - Module 2 | Lesson 6

1 What is a Regular Expression?

A Regular Expression (regex) is a sequence of characters that defines a search pattern. It is one of the most powerful tools for working with text, and it exists in almost every programming language — Java, Python, JavaScript, C++, PHP, and more.

Why Learn Regex?

Without regex, you might write tens of lines of loops and conditionals to validate, search, or clean a String. With a regular expression, you can often express the same logic in a single line.

  • Validate user input (email, phone, password)
  • Extract numbers or words from a messy string
  • Split a string by any non-word delimiter
  • Replace patterns without writing loops

In Java, the String class has three methods that accept a regular expression directly:

Method Description
matches(String regex) Returns true if the entire string matches the pattern
replaceAll(String regex, String replacement) Replaces every match of the pattern with the replacement
split(String regex) Splits the string at every match of the pattern

2 Basic Metacharacters

Metacharacters are special symbols in regex that have a specific meaning. The table below shows the most important ones:

Pattern Meaning Example Match
. Any single character (except newline) "a", "9", "$"
ab|cd Either ab OR cd (alternation) "ab" or "cd"
[abc] Any one of a, b, or c "a", "b", or "c"
[^abc] Any character except a, b, or c "x", "9", "Z"
[a-z] Any lowercase letter from a to z "m", "z"
[A-Z] Any uppercase letter "A", "Z"
[0-9] Any digit from 0 to 9 "3", "7"
Example: Dot (.) — Match Any Single Character

The pattern c.t matches any 3-character string starting with c, then any character, then t:

  • "cat"
  • "cut"
  • "c9t"
  • "ct" ✗ (too short — dot requires exactly one character)
Example: Alternation (|) — Either/Or

The pattern apple|orange matches either the word apple or the word orange:

String fruit = "apple"; System.out.println(fruit.matches("apple|orange")); // true fruit = "orange"; System.out.println(fruit.matches("apple|orange")); // true fruit = "mango"; System.out.println(fruit.matches("apple|orange")); // false
Example: Character Class [ ] — One Of These

The pattern [aeiou] matches any single vowel:

  • [abc] → matches a, b, or c
  • [^abc] → matches anything except a, b, or c
  • [a-zA-Z] → matches any letter (upper or lower)

3 Predefined Character Classes

Java provides shorthand codes (called predefined character classes) so you don't have to write out ranges like [0-9] every time. In Java strings, you write a double backslash \\ to represent a single backslash in the regex.

Pattern (in Java String) Meaning Equivalent to
\\d A digit [0-9]
\\D A non-digit [^0-9]
\\w A word character (letter, digit, or underscore) [a-zA-Z0-9_]
\\W A non-word character [^a-zA-Z0-9_]
\\s A whitespace character (space, tab, newline) [ \t\n\r]
\\S A non-whitespace character [^ \t\n\r]
Double Backslash in Java!

In Java, the backslash \ is a special character in strings. To write the regex \d, you must type "\\d" in your Java code. The first \ is an escape character; together \\ means a literal backslash.

String text = "Hello 2025"; // Does the string contain only digits? System.out.println("12345".matches("\\d+")); // true — all digits System.out.println("abc".matches("\\d+")); // false — no digits // Does the string contain only word characters? System.out.println("Hello_123".matches("\\w+")); // true System.out.println("Hello 123".matches("\\w+")); // false — space is not \w

Quantifiers — How Many Times?

The + after a pattern means "one or more". Here are the most common quantifiers:

  • + — one or more (e.g., \\d+ means one or more digits)
  • * — zero or more
  • ? — zero or one (optional)
  • {n} — exactly n times (e.g., \\d{3} = exactly 3 digits)
  • {n,m} — between n and m times

4 Using replaceAll() to Clean Strings

One of the most practical uses of regex is cleaning data. Suppose you receive a string like a ticket number that mixes letters and digits, and you want to extract only the numbers — no loops needed!

🔑 Example 1: Extract Numbers from a Ticket Code

A ticket like "TKT-2025-AB-001" contains the numbers 2025 and 001. Instead of writing a loop, use replaceAll to remove everything that is not a digit:

String ticket = "TKT-2025-AB-001"; // Replace every non-digit character with an empty string String numbersOnly = ticket.replaceAll("\\D", ""); System.out.println(numbersOnly); // 2025001

\\D means "any non-digit character." Replacing each one with "" removes it, leaving only digits. No loop required.

🧹 Example 2: Replace Multiple Spaces with One Space
String messy = "Hello World Java"; // Replace one or more whitespace characters with a single space String clean = messy.replaceAll("\\s+", " "); System.out.println(clean); // Hello World Java
📸 Example 3: Remove All Non-Letter Characters

Suppose you want only the letters from a string — remove everything that is not a letter:

String raw = "J4v@-Pr0gr@mm!ng"; // Keep only letters (a-z and A-Z) String lettersOnly = raw.replaceAll("[^a-zA-Z]", ""); System.out.println(lettersOnly); // JvrPrgrmmng

5 Using split() with Regex

The split() method divides a string into an array of parts wherever the pattern matches. Unlike a simple character split, regex lets you split on any combination of delimiters.

Example 1: Split by Any Non-Word Character

Sometimes data uses inconsistent separators — commas, semicolons, spaces, dashes. Use \\W+ to split on any sequence of non-word characters:

String data = "apple;banana, cherry - date"; // Split wherever there is one or more non-word characters String[] fruits = data.split("\\W+"); for (String f : fruits) { System.out.println(f); } // apple // banana // cherry // date
🔢 Example 2: Extract Numbers from a Sentence

If you split on non-digits, every remaining piece will be a digit sequence:

String sentence = "Room 101, Floor 3, Building 7"; // Split on non-digit sequences to isolate numbers String[] numbers = sentence.split("\\D+"); for (String n : numbers) { if (!n.isEmpty()) { System.out.println(n); } } // 101 // 3 // 7
📷 Example 3: Split by Multiple Delimiters

Split a CSV-like string that might use commas, semicolons, or pipes as separators:

String csv = "Alice,Bob;Charlie|Dave"; // Split on comma, semicolon, or pipe String[] names = csv.split([,;|]); // Note: | must be escaped in regex: [,;|] for (String name : names) { System.out.println(name); } // Alice // Bob // Charlie // Dave

6 Practical Example: Password Validation

Password validation is one of the most common real-world uses for regular expressions. Instead of writing multiple if conditions and loops, a single matches() call can check all rules at once.

Password Rules
At least 8 characters long
Contains at least one uppercase letter
Contains at least one lowercase letter
Contains at least one digit
Contains at least one special character
No whitespace allowed
public static boolean isValidPassword(String password) { // Rule 1: At least 8 characters long if (password.length() < 8) return false; // Rule 2: Must contain at least one uppercase letter if (!password.matches(".*[A-Z].*")) return false; // Rule 3: Must contain at least one lowercase letter if (!password.matches(".*[a-z].*")) return false; // Rule 4: Must contain at least one digit if (!password.matches(".*\\d.*")) return false; // Rule 5: Must contain at least one special character if (!password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) return false; // Rule 6: No whitespace allowed if (password.matches(".*\\s.*")) return false; return true; }
// Testing the password validator System.out.println(isValidPassword("hello")); // false — too short, no uppercase, no digit System.out.println(isValidPassword("Hello12345")); // false — no special character System.out.println(isValidPassword("Hello 1@3")); // false — has whitespace System.out.println(isValidPassword("Hello1@World")); // true — passes all rules!

Understanding .*[A-Z].*

The pattern .*[A-Z].* means:

  • .* — zero or more of any character (before the uppercase letter)
  • [A-Z] — exactly one uppercase letter
  • .* — zero or more of any character (after the uppercase letter)

Together: the string can have anything, as long as somewhere in it there is at least one uppercase letter.

7 Summary: Quick Reference

Pattern Meaning
. Any single character
a|b a OR b
[abc] a, b, or c
[^abc] Any character except a, b, c
\\d A digit (0–9)
\\D A non-digit
\\w A word character (letter, digit, _)
\\W A non-word character
\\s A whitespace character
\\S A non-whitespace character
+ One or more of the preceding pattern
* Zero or more of the preceding pattern
.* Zero or more of any character
{n} Exactly n repetitions

Key Takeaway

Regular expressions exist in nearly every programming language. The patterns you learned here — \\d, \\w, \\s, character classes, and quantifiers — work the same in Python, JavaScript, and more. Learning regex in Java means you already know regex almost everywhere!