Java Study Materials Regex
Java Study Materials Regex
Regex Introduction
Java
[Link] Package
Study Materials
Pattern Class Methods
Character Classes
─────────────────
Each module includes concept review, code examples & a 30-minute assignment
02 [Link] Package
MODULE 01
Regex in Java
04 Matcher Class Methods
05 Character Classes
07 Quantifiers
08 PatternSyntaxException
09 MatchResult Interface
10 30-Min Assignment
What is Java Regex?
Regular Expression (Regex) is an API to define patterns for searching, validating, or manipulating strings. Introduced in Java 1.4 via the [Link] package.
🔍
Pattern Matching
✅
Validation
🔄
Find & Replace
Match a string against a pattern — e.g. check if text contains the Validate formats such as email addresses, phone numbers, ZIP Search all occurrences of a pattern in text and replace them
word 'error'. codes, passwords. programmatically.
The package contains 3 classes and 1 interface that work together to process regular expressions.
CLASS Pattern
Compiled representation of a regular expression. Use [Link](regex) to create an instance. Provides methods: matches(), compile(), matcher(), split(), pattern().
CLASS Matcher
Engine that performs match operations on character sequences by interpreting a Pattern. Provides: find(), start(), end(), group(), matches().
CLASS PatternSyntaxException
Thrown when a regex pattern string contains a syntax error. Extends IllegalArgumentException (unchecked).
INTERFACE MatchResult
Represents the result of a match operation. Contains query methods such as start(), end(), group() to inspect the result.
Pattern Class — Methods Overview
Compiles regex and tests if the entire input matches. Best for single-use checks. Returns true/false.
Compiles regex into a reusable Pattern object. Use when matching the same pattern multiple times.
Creates a Matcher for the given input sequence against this compiled pattern.
Splits input string around matches of this pattern. Returns an array of the split tokens.
Returns the regex string from which this Pattern was compiled (the source pattern string).
Pattern Class — Code Examples
String text = "This is the text to be searched"; String text = "Link: [Link]
String pattern = ".*is.*"; String str = ".*[Link]
boolean matches = [Link](pattern, text); Pattern pattern = [Link](str);
[Link]("matches = " + matches); Matcher matcher = [Link](text);
// Output: matches = true [Link]([Link]()); // true
💡 Tip: Use [Link]() for one-time checks. Use [Link]() when the same regex is needed multiple times — it avoids recompilation overhead.
Matcher Class — find(), start(), end()
The Matcher class searches through text for multiple occurrences of a pattern and retrieves positional info.
Finds the next subsequence matching the regex. Returns true if found. Starts
at index 0 by default. String regex = "ACA";
Pattern p = [Link](regex);
String s = "ACb AbR ACA";
Matcher m = [Link](s);
while ([Link]()) {
start() — public int start()
[Link]("start:" + [Link]() + " end:" + [Link]());
}
Returns the start index of the previous match. Throws IllegalStateException // Output: start:8 end:11
if no match has been found yet.
A character class is a set of characters inside square brackets [ ]. The regex engine matches ONE character from that set against a single character in the input.
[^abc] Any char EXCEPT 'a', 'b', 'c' Negation — matches any single character not in the set
[a-zA-Z] Any upper or lowercase letter Covers entire alphabet — case-insensitive character match
Metacharacters have pre-defined meanings. Quantifiers specify how many times a character or group can appear.
METACHARACTERS QUANTIFIERS
Represents the result of a match operation. Implemented by Matcher. Query methods: start(), end(),
group(), groupCount().
Thrown when a regex pattern string has a syntax error. Extends IllegalArgumentException (unchecked
exception). Occurs at [Link]() time.
MatchResult — group() and end()
5 min 10 min
01 03
Write a Java program that uses [Link]() to validate whether a given string is a valid email address. Test with: Use [Link]() to count and print every occurrence of the word "the" (case-insensitive) in a given paragraph. Print
"user@[Link]" (valid), "user@.com" (invalid), "[Link]+tag@[Link]" (valid). the start index of each occurrence. Input text: "The quick brown fox. The fox jumped over the lazy dog and the fence."
Regex hint: ^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$ Hint: Use [Link]("the", Pattern.CASE_INSENSITIVE) and call [Link]() in a while(find()) loop.
5 min 10 min
02 04
Given the string: "Alice,30,Engineer,Bangalore,India" — use [Link]() to extract each field. Then validate: (a) age
Validate Indian mobile numbers (10 digits, starting with 6-9). Use [Link]() and Matcher. Test with:
field is exactly 2 digits using \\d{2}, (b) city starts with a capital letter using [A-Z][a-z]+. Print all fields and validation
"9876543210" (valid), "1234567890" (invalid), "98765" (invalid, too short).
results.
Regex hint: ^[6-9][0-9]{9}$ Hint: Split on comma pattern, then run separate [Link]() on the extracted tokens.
TOPICS COVERED
01 Errors in Java
MODULE 02
03 What are Exceptions?
Exception Handling
04 Checked vs Unchecked
in Java 06 ArithmeticException
09 IOException Family
12 30-Min Assignment
Errors in Java — Types & Overview
An error is anything that makes a program go wrong — producing incorrect output, terminating execution, or crashing.
Occurs while the program is executing. Compilation succeeds but behaviour is incorrect or the
Detected by the Java compiler before the program runs. No .class file is produced.
program crashes.
An Exception is an abnormal condition at runtime. Java wraps it in an object (extends Throwable) and throws it.
Throwable
Error Exception
Must be declared with throws or handled with try-catch. Compiler enforces this. Examples: IOException, Extend RuntimeException. No throws declaration needed. Compiler does NOT enforce. Examples:
ClassNotFoundException, FileNotFoundException, InterruptedException. NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.
Java provides many built-in exception classes. The table below covers the 12 most important ones in this module.
Cause Cause
Thrown when arithmetic operation fails — most commonly division by zero. Extends RuntimeException. Thrown when calling a method or accessing a field on a null reference. Most common Java runtime error.
Best Practice
Always check if a reference is null before calling methods on it. Use Optional<T> in Java 8+.
NumberFormatException & ClassCastException &
StringIndexOutOfBoundsException
NumberFormatException ClassCastException StringIndexOutOfBoundsException
ClassNotFoundException FileNotFoundException
[Link]("X") — class not on classpath new FileReader(path) — file does not exist at path
IOException InterruptedException
NoSuchFieldException NoSuchMethodException
[Link]("x") — field absent via reflection [Link]("f") — method absent via reflection
Exception Handling Keywords
Java provides 5 keywords for structured exception handling. Together they give complete control over error flows.
Always executes after try/catch, Manually throw an exception object: Declares that a method may throw
Wraps code that might throw an Catches a specific exception type
regardless of whether an exception throw new checked exceptions: public void m()
exception. Must be followed by at thrown by the try block. Multiple
was thrown. Used for cleanup (closing ArithmeticException("msg"). Used to throws IOException. Informs the
least one catch or finally block. catch blocks handle different types.
resources). signal custom errors. caller.
try-catch, Multi-catch & Nested try
try {
try { int a[] = new int[5];
int a[] = new int[5]; a[5] = 30 / 0;
int result = a[0] / 0; // ArithmeticException } catch (ArithmeticException e) {
} catch (ArithmeticException e) { [Link]("Task 1 done");
[Link]("Arithmetic error: " + [Link]()); } catch (ArrayIndexOutOfBoundsException e) {
} finally { [Link]("Task 2 done");
[Link]("finally always runs"); } catch (Exception e) { // ← must be LAST
} [Link]("General");
}
try {
int a = 10 / 2; // outer try — OK finally always runs — even if return is called inside try/catch.
try {
int b = 10 / 0; // inner try — throws!
throw vs throws: throw creates and sends an exception object; throws declares it in the method
} catch (ArithmeticException e) {
signature.
[Link]("Inner catch: " + [Link]());
}
} catch (Exception e) { A try block MUST have at least one catch or finally.
[Link]("Outer catch");
}
// Output: Inner catch: / by zero
Multi-catch (Java 7+): catch (IOException | SQLException e) { } — catches multiple types in one block.
⏱ 30-Min Write complete Java programs for each task. Handle all exceptions explicitly — no uncaught exceptions allowed.
8 min 8 min
01 03
Write a SafeCalculator class with a divide(int a, int b) method. It must catch ArithmeticException and return 0 if Create a custom checked exception InvalidAgeException. Write a method validateAge(int age) that throws this
division by zero is attempted. Also catch NumberFormatException if non-numeric strings are passed via exception if age < 0 or age > 150. In main(), call the method with ages: -5, 25, 200. Catch the exception and print the
[Link](). Print a meaningful error message for each. age and reason.
Use try-catch with two separate catch blocks. Test: divide(10,2)=5, divide(10,0)=0 class InvalidAgeException extends Exception { } — declare it with throws in the method signature
7 min 7 min
02 04
Write a program with an int array of 5 elements. Use a loop to try accessing indices 0 to 7. For each valid index, print Write a program that attempts to read from "[Link]". If FileNotFoundException is caught, create the file and write
the value. Catch ArrayIndexOutOfBoundsException for invalid indices and print "Index X is out of bounds." Use a "File created by fallback" to it. If any other IOException occurs, print the error. Use a finally block to close any open
finally block to print "Loop iteration complete" on every step. resources. Use multi-catch syntax (Java 7+) where appropriate.
Put the try-catch-finally inside the for loop body catch (FileNotFoundException e) creates the file. Use try-with-resources or finally to close streams.
What's Next?
─────────
Review the concepts, attempt the assignments, and run every code example in your IDE. File I/O in Depth
Generics