Introduction to Regular Expressions

Premium Video

This video is available to Premium members or users who have purchased the course.

Sign in to Unlock

A regular expression, commonly called a regex, is a pattern language used to describe and match sets of strings. Instead of writing many conditions to inspect each character manually, you can describe the rule with a compact pattern.

For example:

This pattern describes four uppercase letters, a hyphen, and four digits. It can match a coupon such as SAVE-1234.

Java provides regular-expression support through:

  • Four convenient String methods: matches(), replaceAll(), replaceFirst(), and split().
  • Pattern, which represents a compiled regular expression.
  • Matcher, which applies a compiled pattern to an input and exposes match results.

The regex API is in the java.util.regex package.

Why regex is useful

Regex is often useful for:

  • Validating coupon codes and simple identifiers.
  • Finding dates, prices, or tokens inside text.
  • Replacing or redacting matching content.
  • Splitting controlled input on delimiters.
  • Extracting fields from semi-structured text.

Regex is not a replacement for every parser. For complex formats such as production CSV with quoted and escaped fields, use a dedicated parser library.

2. A First Regex Example: Validate a Coupon Code

Suppose a coupon must contain four uppercase ASCII letters, a hyphen, and four digits.

Output:

true
false
false

The pattern means:

  • [A-Z]: one uppercase ASCII letter.
  • {4}: exactly four repetitions.
  • -: a literal hyphen.
  • \\d: a digit token as seen by the regex engine; Java source needs the doubled backslash.
  • {4}: exactly four digits.

String.matches() checks the entire string, not just a substring. Therefore, the extra digit in SAVE-12345 makes the final result false.

3. The Four String Methods That Accept Regex

Java has four String methods that interpret their regex argument as a regular expression.

MethodPurpose
matches(String regex)Returns true if the entire string matches the regex
replaceAll(String regex, String replacement)Replaces every match
replaceFirst(String regex, String replacement)Replaces the first match
split(String regex)Splits the string around matches and returns a String[]

3.1 matches(): Match the entire string

Output:

false
true
true

The first call is false because the entire input is not exactly SAVE. The second pattern uses .* before and after SAVE, allowing other characters around it.

When the goal is to find a pattern somewhere within a larger string, Pattern and Matcher.find() are usually clearer than wrapping the pattern in .*.

3.2 replaceAll(): Replace every match

A common use is replacing digits in a log message:

Output:

 Order **** failed with code ***

The regex \\d matches one digit at a time, so every digit is replaced.

3.3 replaceFirst(): Replace only the first match

Output:

 dog, cat, cat

3.4 split(): Split around a regex

Output:

 [red, green, blue]

The pipe | is a regex metacharacter meaning alternation (“or”), so \\| is needed to match a literal pipe.

Important: split() takes a regex, not a plain delimiter string. Real-world CSV can contain quoted fields, escaped quotes, and commas inside quoted values. Use a CSV library such as OpenCSV or Apache Commons CSV for production CSV parsing. A simple split(",") is appropriate only for controlled, uncomplicated input.

Performance note

Each call to String.matches(), replaceAll(), replaceFirst(), or split() compiles its regex for that call. This is convenient for occasional operations but may waste work when the same pattern is used repeatedly in a hot loop.

4. Pattern and Matcher

For reusable patterns, Java's main regex API consists of two classes in java.util.regex.

  • Pattern is the compiled representation of a regex.
  • Matcher applies that compiled pattern to a particular input and tracks match state.

Example: Compile once, validate many inputs

Output:

SAVE-1234 -> true
DEAL-9087 -> true
save-1234 -> false
SAVE-12345 -> false

The regex is compiled once outside the loop. A new Matcher is created for each input because a matcher contains mutable state, such as its current position in the input.

A Pattern is immutable and safe to reuse across threads. A Matcher should not be shared concurrently between threads.

Pattern lifecycle flowchart

Whiteboard
Loading diagram...

5. matches(), find(), and lookingAt()

These three Matcher methods answer different questions.

MethodMeaning
matches()Does the entire input match the pattern?
find()Is there a match somewhere from the current search position onward?
lookingAt()Does a match begin at the start of the input, even if more text follows?

Example

Output:

false
true
true

  • matches() returns false because Order 123 is not entirely digits.
  • find() returns true because it finds 123 within the input.
  • lookingAt() returns true because the input starts with digits.

Extracting repeated matches with find()

Output:

$49.99 at [10, 16)
$29.99 at [22, 28)
$89.99 at [36, 42)

group() returns the text matched by the most recent successful match. start() gives the starting index, and end() gives the index just after the match. Java string indices are based on UTF-16 code units.

Each successful find() advances the matcher to search after the previous match. When there are no more matches, find() returns false.

How find() advances

Whiteboard
Loading diagram...


6. Literal Characters and Escaping

Most characters match themselves. For example, cart matches those four letters in order.

The following characters have special meaning in regex syntax:

To match a metacharacter literally, escape it in the regex with a backslash. For example:

  • \\. in Java source represents the regex \. and matches a literal period.
  • \\$ represents the regex \$ and matches a literal dollar sign.
  • \\( represents the regex \( and matches a literal opening parenthesis.

Remember that Java source strings and regex patterns are two separate parsing layers. Section 14 explains the double-escaping rule in detail.

7. Character Classes

A character class matches exactly one character from a specified set.

RegexMeaning
[abc]One of a, b, or c
[a-z]One lowercase ASCII letter
[A-Za-z]One ASCII letter, uppercase or lowercase
[0-9]One digit from 0 through 9
[^0-9]One character that is not an ASCII digit

A caret ^ at the beginning of a character class negates that class. Outside a character class, ^ is commonly an anchor for the start of input.

Example

Output:

AB197

The pattern matches one or more uppercase letters from A through F or digits from 0 through 9. The hyphen and Z are not part of the class, so they separate the matches.

8. Predefined Character Classes

Java regex includes shorthand classes for frequently used character sets.

Regex tokenCommon ASCII-oriented interpretation
\\dA digit; by default, [0-9]
\\DA non-digit
\\wA word character, commonly [A-Za-z0-9_]
\\WA non-word character
\\sA whitespace character
\\SA non-whitespace character
.Any character except a line terminator by default

Exact behavior can depend on regex flags. In Java, Unicode-aware behavior is available through options such as Pattern.UNICODE_CHARACTER_CLASS; consult the Pattern documentation when international text is important.

Example: Find words and numbers

Output:

Box
24
contains
3
books

The \\w+ pattern finds consecutive word characters. It does not include spaces or punctuation.

9. Anchors and Word Boundaries

Anchors match positions, not characters.

AnchorMeaning
^Start of input, subject to flags such as multiline mode
$End of input or an end position as defined by Java regex semantics
\\bWord boundary
\\BPosition that is not a word boundary

A word boundary is a position between a word character and a non-word character, or at the beginning/end of input where a word character meets the boundary.

Example: Find a whole word, not part of another word

Output:

cart at index 0
cart at index 23

The cart inside cartridge is not matched because there is no word boundary after cart.

10. Quantifiers: How Many Times Can a Pattern Repeat?

A quantifier follows a character, character class, or group and specifies how many repetitions are allowed.

QuantifierMeaning
*Zero or more
+One or more
?Zero or one (optional)
{n}Exactly n repetitions
{n,m}Between n and m repetitions
{n,}At least n repetitions

By default, these quantifiers are greedy: they attempt to consume as much matching text as possible while still allowing the overall pattern to succeed.

Greedy versus reluctant (lazy) quantifiers

Adding ? after a quantifier makes it reluctant, meaning it tries to match as little as possible while allowing the full pattern to succeed.

Output:

Greedy: onetwo
Reluctant:
Reluctant:

Reluctant:
Reluctant:

The greedy .+ consumes as much as it can, so the first match stretches from the first < to the last >. The reluctant .+? stops at the earliest point where the rest of the pattern can succeed.

Reluctant quantifiers are useful for simple token extraction, but they do not turn regex into a full parser for nested markup.

Possessive quantifiers

Java also supports possessive forms such as *+, ++, and ?+. A possessive quantifier does not give back characters it has consumed during backtracking. This can improve performance for carefully designed patterns, but it can also change whether a pattern matches.

11. Alternation: Match One Option or Another

The pipe | means “or”.

  • cart|wishlist matches cart or wishlist.
  • (cart|wishlist) page matches cart page or wishlist page.

Parentheses make it clear which part of a pattern the alternatives belong to.

Example: Match simple stock descriptions

Output:

12 stickers
no batteries
4 notebooks

The pattern uses:

  • \\b for a word boundary.
  • (?:\\d+|no) for one or more digits or the word no.
  • \\s+ for one or more whitespace characters.
  • \\w+ for a word.
  • Pattern.CASE_INSENSITIVE to ignore case for matching.

This is a small example of combining multiple regex features in one pattern.

12. Capturing, Named, and Non-Capturing Groups

Parentheses can group expressions and capture the text matched by them.

12.1 Capturing groups

Capturing groups are numbered from left to right by the position of each opening parenthesis. group(0) returns the entire match; group(1) returns the first captured group.

Output:

Full date: 2026-10-19
Year: 2026
Month: 10
Day: 19

12.2 Named capturing groups

Named groups can make patterns easier to maintain. Java syntax is (?<name>...), and the matched value can be read with group("name").

Output:

Type: INVOICEID: 8042

12.3 Non-capturing groups

Use (?:...) when you need parentheses for grouping but do not need to retrieve that group's text. This keeps group numbering tidy.

Output:

 ID: 5821

The alternatives are grouped without capturing them, so the numeric identifier is group 1.

13. Back-References

A back-reference refers to text previously captured by a group in the same match. For example, \\1 in Java source represents regex back-reference \1, which matches the same text captured by group 1.

Example: Find adjacent duplicate words

Output:

is is
test test

Here, (\\w+) captures a word and \\1 requires the next word to contain the same text. Back-references are powerful, but patterns that combine them with ambiguous repetition can be expensive on long or adversarial input.

14. The Double-Escaping Rule in Java

This is one of the most common sources of Java regex mistakes.

There are two parsers involved:

  1. The Java compiler interprets the Java string literal.
  2. The regex engine interprets the resulting string as a pattern.

Therefore, a backslash intended for the regex usually needs to be doubled in an ordinary Java string literal.

Regex pattern needed by the regex engineJava string literal
\\d as regex text means digit token \d"\\d"
\\s as regex text means whitespace token \s"\\s"
\\. as regex text means literal period \."\\."
\\\\ as regex text means literal backslash \\"\\\\"
\\b as regex text means word boundary \b"\\b"

The table displays the Java source form in the right column. In the regex column, the actual regex syntax is shown with its single regex backslashes.

Example: Match a price with two decimal places

Incorrect Java source such as "\$\d+\.\d{2}" does not compile because sequences like \$, \d, and \. are not valid Java string escapes.

Correct code:

Output:

true
false

The regex means a literal dollar sign, one or more digits, a literal period, and exactly two digits.

Text blocks

Java text blocks (available from Java 15) make multiline strings easier to read. They still process Java escape sequences, so regex backslashes generally still need escaping inside text blocks. Text blocks improve formatting, but they do not eliminate the double-escaping rule.

When patterns fail to compile

Java cannot fully validate a regex pattern at ordinary Java compile time because the regex is usually just a string. A malformed pattern can cause PatternSyntaxException when Pattern.compile() executes. For fixed patterns, compiling them in a static final Pattern field can make invalid patterns fail early during class initialization.

15. Performance: Compile a Reusable Pattern Once

For a one-off check, String.matches() is convenient. If the same regex is evaluated many times, compile it once and reuse the Pattern.

Output:

SAVE-1234 -> true
DEAL-0088 -> true
save-1234 -> false

This design avoids recompiling the regex on every iteration. The exact speedup depends on the JVM, workload, and pattern; avoid claiming a universal multiplier without measuring your own application.

Practical performance guidance

  • Compile fixed, frequently used patterns once.
  • Reuse the immutable Pattern.
  • Create a separate Matcher for each input or operation.
  • Keep patterns as simple and unambiguous as possible.
  • Benchmark realistic inputs before optimizing based on assumptions.

16. Catastrophic Backtracking

Some regexes can take an extremely long time on inputs that nearly match but fail at the end. This is often called catastrophic backtracking.

A classic risky shape is a nested quantifier with overlapping possibilities, such as:

There are many ways to divide a long run of a characters among the inner and outer repetitions. If the overall match fails near the end, a backtracking engine may explore many alternatives.

A more realistic risky validation pattern is:

The repeated group allows word characters and optional whitespace. With certain near-matching inputs, the repeated parts can overlap in ways that cause excessive backtracking.

Prefer a less ambiguous pattern

If the requirement is “one or more words separated by whitespace,” a clearer pattern is:

This describes one word followed by zero or more groups of whitespace plus another word. It avoids the particular overlap in the earlier expression.

Possessive quantifiers can help when appropriate

Possessive quantifiers prevent a quantifier from giving back characters during backtracking. They can make some patterns fail faster, but they must be used only when the intended matching behavior is preserved.

Backtracking safety checklist

  • Avoid nested repetition when repeated sections can match the same characters.
  • Prefer a pattern that expresses the input grammar directly.
  • Test long, malformed, near-matching input—not just successful examples.
  • Treat user-controlled input as potentially adversarial.
  • Use regex engines or validation strategies with appropriate resource controls for high-risk workloads. Java's standard regex API does not expose a simple per-match timeout setting on Matcher.

17. The Dot (.) Surprise

In regex, . means “any character except a line terminator by default.” It does not mean a literal period.

Incorrect: Replace every character by accident

Output:

 *********

The regex . matched every character in the string, so every character was replaced.

Correct: Match a literal period

Output:

 version 2[dot]1 and version 3[dot]0

The Java string "\\." becomes regex \. and matches only literal periods. If the input contains no periods, the replacement would leave it unchanged.

18. Putting It Together: Redact a Card Number in an Order Log

Suppose an order log contains a 16-digit card number. Before writing the log to disk, the application should hide the first 12 digits and preserve the final four digits for support verification.

Output:

 Order 7812 payment card ************3456 approved

How the pattern works:

  • \\b requires a word boundary.
  • (\\d{12}) captures the first 12 digits.
  • (\\d{4}) captures the final four digits.
  • The second \\b requires a boundary after the full 16-digit sequence.
  • In a replacement string, $2 inserts the text captured by group 2.

The word boundaries help prevent matching a 16-digit substring inside a larger uninterrupted word/digit sequence. This is an illustrative text-redaction example, not a substitute for a payment provider's security guidance or a comprehensive card-data handling design.

19. Choosing the Right Regex API

Use this guide when selecting an API.

Whiteboard
Loading diagram...


RequirementRecommended approach
Check whether the whole string matches a small pattern onceString.matches()
Replace every occurrenceString.replaceAll()
Replace only the first occurrenceString.replaceFirst()
Split controlled input on a regex delimiterString.split()
Search for or extract repeated matchesPattern + Matcher.find()
Reuse a fixed pattern many timesstatic final Pattern
Parse a complex structured formatPrefer a dedicated parser/library

20. Common Mistakes to Avoid

MistakeWhy it is wrongBetter approach
Using matches() to search for a substringmatches() requires the entire input to matchUse Matcher.find()
Writing "\d+" in Java source\d is not a valid Java string escapeWrite "\\d+"
Using "." to match a literal periodDot is a regex wildcardUse "\\."
Passing `directly tosplit()`Pipe means alternation in regex
Compiling the same pattern in a hot loopRepeats compilation workReuse a Pattern
Sharing a Matcher across threadsMatcher state is mutableCreate separate matchers
Using nested ambiguous quantifiersCan cause excessive backtrackingRewrite to reduce ambiguity
Using regex as a full CSV parserQuoted and escaped fields need more robust parsingUse a CSV library
Assuming \\w always covers every language's lettersCharacter-class behavior depends on flags and definitionsCheck Unicode requirements and configure/test accordingly

21. Quick Reference: Java Regex Syntax

CategoryRegex syntaxMeaningJava source form
LiteralaLiteral character a"a"
Escaping\.Literal period"\\."
Escaping\$Literal dollar sign"\\$"
Character class[abc]One of a, b, c"[abc]"
Character class[a-z]One lowercase ASCII letter"[a-z]"
Negated class[^0-9]One non-ASCII-digit character"[^0-9]"
Predefined\dDigit"\\d"
Predefined\DNon-digit"\\D"
Predefined\wWord character under current regex settings"\\w"
Predefined\WNon-word character"\\W"
Predefined\sWhitespace"\\s"
Predefined\SNon-whitespace"\\S"
Wildcard.Any character except line terminators by default"."
Anchor^Start position"^"
Anchor$End position as defined by Java regex semantics"$"
Boundary\bWord boundary"\\b"
Quantifier*Zero or more"*"
Quantifier+One or more"+"
Quantifier?Zero or one"?"
Quantifier{n}Exactly n"{n}"
Quantifier{n,m}Between n and m"{n,m}"
Reluctant*?, +?, ??Prefer the shortest match that allows success"*?"
Possessive*+, ++, ?+Do not give back matched characters"*+"
Alternation`ab`a or b
Group( ... )Capturing group"( ... )"
Group(?: ... )Non-capturing group"(?: ... )"
Named group(?<name>...)Named capture"(?<name>...)"
Back-reference\1Text captured by group 1"\\1"

For complete syntax, flags, Unicode property escapes, character-class intersections, and exact matching behavior, consult the official Java Pattern documentation:
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html

22. Best Practices for Java Regex

  1. Write the rule in plain language first. For example, “four uppercase letters, a hyphen, four digits.”
  2. Use matches() only for whole-input validation. Use find() for searching within text.
  3. Compile reusable patterns once. A static final Pattern is appropriate for a fixed application-level regex.
  4. Keep each Matcher local to the operation. It holds mutable matching state.
  5. Escape regex metacharacters deliberately. A literal period is \\. in Java source, not ".".
  6. Test boundary cases. Include empty strings, too-short and too-long inputs, unexpected punctuation, and trailing characters.
  7. Be cautious with user-controlled input. Avoid patterns with nested, ambiguous quantifiers that can cause catastrophic backtracking.
  8. Use named groups when they improve readability. They are useful when patterns capture multiple fields.
  9. Prefer dedicated parsers for complex formats. Regex is useful for token patterns, but not always for nested or escaped data formats.
  10. Document non-obvious patterns. A short comment explaining the intended format helps future maintenance.

23. Quick Revision

  • A regex is a pattern for matching text.
  • String.matches() checks the whole string.
  • replaceAll() replaces all matches; replaceFirst() replaces the first match.
  • split() uses a regex delimiter.
  • Pattern is compiled and reusable; Matcher holds state for a particular input.
  • Matcher.matches(), find(), and lookingAt() have different matching scopes.
  • Character classes such as [A-Z] match one character from a set.
  • Quantifiers such as *, +, ?, and {n} control repetition.
  • Parentheses capture groups; (?:...) groups without capturing; (?<name>...) names a capture.
  • Java string literals usually need doubled backslashes for regex escapes.
  • . is a wildcard; use \\. to match a literal period.
  • Reuse compiled patterns and avoid ambiguous nested quantifiers on untrusted input.

24. Conclusion

Regular expressions give Java developers a concise way to validate, search, extract, split, and transform text. Start with the String shortcuts for simple operations, then use Pattern and Matcher when you need reusable patterns, repeated searches, or captured groups.

The most important habits are to understand whole-string matching versus searching, escape backslashes correctly in Java strings, compile frequently reused patterns once, and design patterns carefully to avoid excessive backtracking. With these fundamentals, regex becomes a practical tool for everyday text processing rather than a source of mysterious bugs.