Nearby lessons
108 of 125Java - Regular Expressions
- 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).
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.
Character Classes
Character classes match a set of characters. They are written inside square brackets [...].
| Pattern | Matches |
|---|---|
| [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 |
Predefined Character Classes (Shortcuts)
| Pattern | Meaning | Simple words |
|---|---|---|
| \d | digit | 0-9 |
| \D | not a digit | letters, symbols |
| \w | word character | letters + digits + underscore |
| \W | not a word character | symbols like @ # |
| \s | space | space, tab, newline |
| \S | not a space | everything except space |
| . | any character | any single character |
Quantifiers — How Many Times
Quantifiers say how many times the previous character should appear.
| Quantifier | Meaning | Example |
|---|---|---|
| a* | 0 or more a's | "", a, aa, aaa |
| a+ | 1 or more a's | a, aa, aaa (at least one) |
| a? | 0 or 1 a (optional) | "" or a |
| a{3} | exactly 3 a's | aaa |
| a{2,4} | 2 to 4 a's | aa, aaa, aaaa |
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.
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:
| Method | What 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. |
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 [.].
- 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.