Nearby lessons

108 of 125

Java - Regular Expressions

📌 What You Will Learn
  • What a regular expression (regex) is
  • Pattern and Matcher — the two main classes
  • Character classes and quantifiers
  • Validating things like phone numbers and emails
  • The easy String methods: matches, replaceAll, split

Regular Expressions is a core concept of the Java language. This lesson explains What is a Regular Expression?, First Program — Pattern and Matcher and Character Classes with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is a Regular Expression?

A regular expression (regex) is a pattern written as text, used to search, match and replace inside other text. It is like a smart search box that understands rules, not just exact words.

Example: the pattern [0-9]{10} means exactly 10 digits. You can use it to check whether a mobile number is valid. One small pattern does what pages of normal code would need.

Java gives us regex through the java.util.regex package, mainly with two classes: Pattern (the compiled pattern) and Matcher (the engine that searches with it).

In simple words: A regex is just a pattern written as text. You describe what to search for — like 10 digits or a letter followed by a digit — and Java finds every place that fits that description.

First Program — Pattern and Matcher

The pattern ab finds every place where the letters a and b appear together. m.find() moves through the text, m.group() gives the matched text, m.start() gives its position.

In simple words: `Pattern` holds the compiled rule and `Matcher` does the searching. You compile the pattern once, then let m.find() scan the text and m.group() pick up each match.
Example02
JCode Cell
1import java.util.regex.*;
2 
3class RegexDemo {
4 public static void main(String[] args) {
5 Pattern p = Pattern.compile("ab"); // the pattern
6 Matcher m = p.matcher("abbbabbaba"); // the text to search
7 
8 while (m.find()) { // keep finding matches
9 System.out.println("Found at " + m.start() + " -> " + m.group());
10 }
11 }
12}
Output
Found at 0 -> ab Found at 4 -> ab Found at 7 -> ab

Character Classes

Character classes match a set of characters. They are written inside square brackets [...].

PatternMatches
[abc]Either a, b, or c
[^abc]Any character EXCEPT a, b, c
[a-z]Any small letter a to z
[A-Z]Any capital letter
[0-9]Any digit
[a-zA-Z0-9]Any letter or digit
Example03
JCode Cell
1Pattern p = Pattern.compile("[a-z]"); // every small letter in the text
2Matcher m = p.matcher("a1B#");
3while (m.find()) {
4 System.out.print(m.group() + " ");
5}
6// prints: a (only 'a' is a small letter)

Predefined Character Classes (Shortcuts)

PatternMeaningSimple words
\ddigit0-9
\Dnot a digitletters, symbols
\wword characterletters + digits + underscore
\Wnot a word charactersymbols like @ #
\sspacespace, tab, newline
\Snot a spaceeverything except space
.any characterany single character
Example04
JCode Cell
1import java.util.regex.*;
2 
3class ShortcutsDemo {
4 public static void main(String[] args) {
5 Pattern p = Pattern.compile("\\d"); // digits only
6 Matcher m = p.matcher("Mobile: 9876543210");
7 while (m.find()) {
8 System.out.print(m.group()); // prints all digits
9 }
10 }
11}
Output
9876543210

Quantifiers — How Many Times

Quantifiers say how many times the previous character should appear.

QuantifierMeaningExample
a*0 or more a's"", a, aa, aaa
a+1 or more a'sa, aa, aaa (at least one)
a?0 or 1 a (optional)"" or a
a{3}exactly 3 a'saaa
a{2,4}2 to 4 a'saa, aaa, aaaa
In simple words: A quantifier decides how many times the previous character may repeat. + means one or more, * means zero or more, and ? means optional — that is why [a-zA-Z0-9]+@gmail.com accepts rahul but rejects an empty email.
Example05
JCode Cell
1import java.util.regex.*;
2 
3class QuantifierDemo {
4 public static void main(String[] args) {
5 // email-id pattern: one or more word chars, then @gmail.com
6 Pattern p = Pattern.compile("[a-zA-Z0-9]+@gmail.com");
7 System.out.println(p.matcher("rahul@gmail.com").matches()); // true
8 System.out.println(p.matcher("rahul@yahoo.com").matches()); // false
9 System.out.println(p.matcher("rahul@gmail.com.in").matches()); // false
10 }
11}
Output
true false false

Anchors and Groups

  • ^ — start of the line (e.g., ^Hello matches lines starting with Hello).
  • $ — end of the line (e.g., end$ matches lines ending with end).
  • ( ) — groups a part, e.g., (ab)+ means one or more 'ab' together.
  • | — OR, e.g., cat|dog matches cat or dog.
Example06
JCode Cell
1Pattern p = Pattern.compile("^(a|b)+c");
2// matches: c, ac, bc, abac ... (a/b repeated, ends with c)

The Easy Way — String Methods with Regex

Since Java 1.4, the String class itself has regex methods. These are the ones you will use most in real code:

MethodWhat it does
matches(regex)true if the WHOLE string matches the pattern.
replaceAll(regex, replacement)Replace every match with the replacement.
replaceFirst(regex, replacement)Replace only the first match.
split(regex)Break the string into an array using the pattern.
In simple words: `matches()`, `replaceAll()` and `split()` put the regex engine inside the String itself. For most real-life jobs — validating a mobile number or cleaning messy input — these one-line methods are all you need.
Trainer's Note: Trainer tip: the most practical regex skills for a student are (1) validating mobile/email/PAN, (2) extracting numbers from text, and (3) cleaning messy input. Practise those three and you will use regex confidently in real projects. Remember: \d in a Java String literal must be written "\\d" because the backslash itself needs escaping.
Example07
JCode Cell
1class StringRegex {
2 public static void main(String[] args) {
3 // 1. validate a 10-digit mobile number
4 String mobile = "9876543210";
5 System.out.println("Valid mobile: " + mobile.matches("[0-9]{10}"));
6 
7 // 2. remove all non-digit characters
8 String pan = "ABC-1234-X";
9 System.out.println("Only digits: " + pan.replaceAll("[^0-9]", ""));
10 
11 // 3. split by any number of spaces
12 String line = "Rahul Delhi 99";
13 String[] parts = line.split("\\s+");
14 System.out.println("Parts: " + parts.length); // 3
15 }
16}
Output
Valid mobile: true Only digits: 1234 Parts: 3

The Dot — Special Character vs Literal

The dot . is special in regex — it matches any character. But what if you want to match a literal dot (like the full stop in a file name)? You must escape it: \. or put it in a character class [.].

Trainer's Note: Trainer tip: this dot trap confuses everyone once. Remember — in Java code, the escaped dot is written "\\." because the backslash itself is escaped in a String literal (exactly like \\d for digits).
Example08
JCode Cell
1Pattern p = Pattern.compile("."); // matches ANY character
2Pattern p = Pattern.compile("\\."); // matches a literal dot
3Pattern p = Pattern.compile("[.]"); // matches a literal dot (same)
4 
5// Example: split an email or web address by the dot
6String s = "www.example.com";
7String[] parts = s.split("\\."); // -> ["www", "example", "com"]
8System.out.println(java.util.Arrays.toString(parts));
Output
[www, example, com]
📝 Key Takeaways
  • A regex is a pattern to search/match text.
  • Pattern.compile() builds the pattern; Matcher.find() searches.
  • Character classes [abc], [a-z] and shortcuts \d \w \s make patterns compact.
  • Quantifiers: * (0+), + (1+), ? (optional), {n} (exact count).
  • String methods matches(), replaceAll(), split() do most practical regex work.
  • In Java code, write \d as "\\d" because of escaping.

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10