Java Regular Expressions
Describe a text pattern, then choose the matching operation.
Read this topic in தமிழ் ↗.
By the end of this lesson, you can…
- Explain the key idea behind Regular Expressions.
- Read and run a complete example, then predict what changes.
- Recognize the topic-specific mistake discussed below.
Understand the idea
A regular expression describes a set of text patterns. matches checks the entire input; find searches for a matching region. Keep Java string escaping separate from regex escaping when a pattern contains backslashes.
Explore the details
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.
Java does not have a built-in Regular Expression class, but we can import the java.util.regex
package to work with regular expressions. The package includes the following
classes:
PatternClass – Defines a pattern (to be used in a search)MatcherClass – Used to search for the patternPatternSyntaxExceptionClass – Indicates syntax error in a regular expression pattern
Example Explained
In this example, The word "codingtamilan" is being searched for in a sentence.
First, the pattern is created using the Pattern.compile() method. The first parameter
indicates which pattern is being searched for and the second parameter has a flag to
indicates that the search should be case-insensitive. The second parameter is optional.
The matcher() method is used to search for the pattern in a string. It returns a Matcher
object which contains information about the search that was performed.
The find() method returns true if the pattern was found in the string and false if it was not
found.
import java.util.regex.*;
// Basic match
Pattern p = Pattern.compile("codingtamilan", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I love CodingTamilan!");
System.out.println(m.find()); // true
// Full-string match
System.out.println("Hello".matches("[A-Z][a-z]+")); // true
// Find all occurrences
Pattern pAll = Pattern.compile("cat");
Matcher mAll = pAll.matcher("cat and cats and catch");
while (mAll.find()) {
System.out.println("Found at index " + mAll.start());
}
// Found at index 0
// Found at index 8
// Found at index 17Flags
Flags in the compile() method change how the search is performed. Here are a few of
them:
Pattern.CASE_INSENSITIVE– The case of letters will be ignored when performing a search.Pattern.LITERAL– Special characters in the pattern will not have any special meaning and will be treated as ordinary characters when performing a search.Pattern.UNICODE_CASE– Use it together with theCASE_INSENSITIVEflag to also ignore the case of letters outside of the English alphabet
Regular Expression Patterns
The first parameter of the Pattern.compile() method is the pattern. It describes what
is being searched for.
Brackets are used to find a range of characters:
| Expression | Description |
|---|---|
| [abc] | Find one character from the options between the brackets |
| [^abc] | Find one character NOT between the brackets |
| [0-9] | Find one character from the range 0 to 9 |
Metacharacters
Metacharacters are characters with a special meaning:
| Metacharacter | Description |
|---|---|
| | | Find a match for any one of the patterns separated by | as in: cat|dog|fish |
| . | Find just one instance of any character |
| ^ | Finds a match as the beginning of a string as in: ^Hello |
| $ | Finds a match at the end of the string as in: World$ |
| \d | Find a digit |
| \s | Find a whitespace character |
| \b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
| \uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
Quantifiers
Quantifiers define quantities:
| Quantifier | Description |
|---|---|
| n+ | Matches any string that contains at least one n |
| n* | Matches any string that contains zero or more occurrences of n |
| n? | Matches any string that contains zero or one occurrences of n |
| n{x} | Matches any string that contains a sequence of X n's |
| n{x,y} | Matches any string that contains a sequence of X to Y n's |
| n{x,} | Matches any string that contains a sequence of at least X n's |
Real-World Regex Examples
| Use case | Pattern | Notes |
|---|---|---|
[\w.-]+@[\w.-]+\.[a-zA-Z]{2,} | Basic; use a library for production | |
| Indian phone | [6-9]\d{9} | 10-digit, starts 6–9 |
| Digits only | \d+ | One or more digits |
| Alphanumeric | [a-zA-Z0-9]+ | Letters and digits |
| Date dd/mm/yyyy | (0[1-9]|[12]\d|3[01])/(0[1-9]|1[0-2])/\d{4} | Strict day/month range |
// String.matches() — full-string regex test
String email = "user@example.com";
System.out.println(email.matches("[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}")); // true
// replaceAll — remove all non-digits
String cleaned = "Phone: 98-765-43210".replaceAll("\\D", "");
System.out.println(cleaned); // 9876543210
// split by whitespace
String[] words = "hello world java".split("\\s+");
System.out.println(Arrays.toString(words)); // [hello, world, java]A complete runnable example
This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Pattern.matches("[A-Z][0-9]{3}", "A123"));
System.out.println(Pattern.matches("[A-Z][0-9]{3}", "A1234"));
}
}Predict first. Then reveal the expected output / வெளியீடு
true false
The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.
Change it. Run it. Understand it.
Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.
Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.
Make it your own
Practice challenge
Try a123 and B007. Which inputs satisfy the pattern?
Reveal the answer and reasoning / விடை
a123 fails because the first character is lowercase; B007 matches.
One mistake to avoid: Pattern.matches is a whole-input check. It does not mean that any matching substring is enough.
Your learning checkpoint
- Explain the example without reading the output first.
- Make the change requested in the practice task.
- Describe why the result changed—or why compilation failed.
Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.