Java Regular Expressions: Syntax, Character Classes and Quantifiers
The java.util.regex pattern language: literals and metacharacters, character classes with ranges, negation and intersection, \d \w \s and Unicode \p{...} classes, greedy, reluctant and possessive quantifiers, groups and back-references, boundaries, lookaround, and escaping.
kvi5hnuCode Sprout team member11 min readOn this page
A regular expression (regex) is a compact description of a set of strings. You use one to check that input has the right shape, to find every occurrence of something in a text, to split text into pieces, or to rewrite parts of it. Java's support lives in java.util.regex, mainly the classes Pattern and Matcher. This article covers the pattern language itself. The next two put it to work.
Java's dialect is close to Perl's, but not identical, and every library differs in small ways. When in doubt, the Pattern class documentation is the authoritative reference.
Literals and metacharacters
Most characters simply match themselves: the pattern Java matches the string Java. These characters have special meanings:
. * + ? { } [ ] ( ) | \ ^ $
.matches any single character except a line terminator.|separates alternatives..(oo|ee)fmatchesbeefandwoof. Without parentheses, alternation covers everything on each side:.oo|eefmeans ".oooreef".( )group things together, for alternation, for quantifiers, and to capture text (see below).\escapes a metacharacter or introduces a special sequence.
To match a metacharacter literally, put a backslash in front of it (\., \$, \(), or quote a whole stretch with \Q...\E. Both \(\$0\.99\) and \Q($0.99)\E match the string ($0.99).
When the text to match comes from a variable, don't escape it by hand. Pattern.quote(s) wraps it in \Q...\E and handles the corner case where s itself contains \E.
Character classes
A character class in square brackets matches one character from a set:
| Class | Matches |
|---|---|
[Jj] | J or j |
[0-9], [A-Za-z] | a range of characters, by code point |
[^0-9] | any character except those listed (^ must be first) |
[0-9+-] | a - at the start or end is literal |
[a-z&&[^aeiou]] | intersection: lowercase consonants |
[\p{L}&&[^A-Za-z]] | letters other than ASCII letters |
Inside brackets, most metacharacters lose their meaning. You only need to escape [ and \, as long as ], ^ and - are placed where they can't be misread. For example, []^-] matches any of those three characters.
Predefined classes save typing:
| Class | Default meaning | With UNICODE_CHARACTER_CLASS |
|---|---|---|
\d, \D | [0-9], and its complement | any Unicode decimal digit |
\w, \W | [a-zA-Z0-9_], and its complement | Unicode letters, marks, digits, connectors |
\s, \S | [ \t\n\x0B\f\r], and its complement | Unicode white space |
\h, \v | horizontal and vertical white space (always Unicode-aware) | |
\R | any line break, including \r\n as one unit | |
. | any character except line terminators (or any character with DOTALL) |
By default \w doesn't match ï, so \w+ fails on naïve. The UNICODE_CHARACTER_CLASS flag, or (?U) inside the pattern, makes the classes follow Unicode (article 38 covers flags).
Unicode properties
\p{...} matches a character with a Unicode property, and \P{...} matches one without it. For a single-letter name the braces are optional, so \pL is the same as \p{L}.
| Form | Example | Meaning |
|---|---|---|
| general category | \p{L}, \p{Lu}, \p{Ll}, \p{N}, \p{P}, \p{Sc} | letter, uppercase letter, lowercase letter, number, punctuation, currency symbol |
| script | \p{IsGreek}, \p{script=Latin} | characters of a writing system |
| block | \p{InGreek}, \p{block=Mongolian} | characters in a Unicode block |
| binary property | \p{IsAlphabetic}, \p{IsWhite_Space}, \p{IsEmoji} | Unicode properties |
| POSIX class | \p{Lower}, \p{Alnum}, \p{Punct}, \p{XDigit} | ASCII sets by default, Unicode with UNICODE_CHARACTER_CLASS |
| Java method | \p{javaUpperCase}, \p{javaWhitespace} | the result of Character.isUpperCase and so on |
The emoji properties (IsEmoji, IsEmoji_Presentation, IsExtended_Pictographic and related ones) were added in Java 21.
Quantifiers
A quantifier says how often the preceding item may repeat:
| Quantifier | Meaning | Example |
|---|---|---|
X? | 0 or 1 | \+? is an optional plus sign |
X* | 0 or more | [1-9][0-9]* is a positive integer with no leading zero |
X+ | 1 or more | be+s? matches be, bee, bees |
X{n} | exactly n | \d{4} |
X{n,} | at least n | \w{3,} |
X{m,n} | between m and n | [0-7]{1,3} is one to three octal digits |
Every quantifier comes in three flavors:
- Greedy (the default) takes as much as possible, then gives characters back one at a time if the rest of the pattern fails. On
<b>bold</b> text,<.+>matches all of<b>bold</b>, which is rarely what you want. - Reluctant (add
?:*?,+?,??,{m,n}?) takes as little as possible and grows only when needed.<.+?>matches just<b>. - Possessive (add
+:*+,++,?+,{m,n}+) takes as much as possible and never gives anything back.a*+anever matches, becausea*+swallows all theas and keeps them. That sounds useless, but it prevents pointless backtracking.'[^']*+'fails immediately on a string with no closing quote, while the greedy version retries every shorter length first.
The same no-backtracking behavior is available for any subpattern as an atomic group, (?>X).
Groups and back-references
Parentheses create a capturing group. Groups are numbered by their opening parenthesis, starting at 1, and the text each one matched can be retrieved afterwards (article 37). Inside the pattern, \n refers back to whatever group n matched. (['"]).*\1 matches 'Fred' and "Fred", but not "Fred', because the closing quote must be the same character as the opening one.
| Syntax | Meaning |
|---|---|
(X) | capturing group |
(?<name>X) | named capturing group; the name starts with a letter and contains only ASCII letters and digits |
\1, \2, ... | back-reference to a numbered group |
\k<name> | back-reference to a named group |
(?:X) | group without capturing, for alternation or quantifiers only |
(?>X) | atomic group: no backtracking into X |
(?i:X), (?-i:X) | group with flags turned on or off (article 38) |
Boundaries and lookaround
These match a position, not a character:
| Syntax | Position |
|---|---|
^, $ | start and end of input, or of each line in MULTILINE mode. $ also matches before a final line terminator |
\A, \z | start and very end of input, always |
\Z | end of input, allowing a final line terminator |
\b, \B | a word boundary, and any position that isn't one |
\b{g} | a boundary between grapheme clusters (user-perceived characters) |
\G | the end of the previous match |
X(?=Y) | X, if followed by Y (lookahead) |
X(?!Y) | X, if not followed by Y |
(?<=Y)X | X, if preceded by Y (lookbehind) |
(?<!Y)X | X, if not preceded by Y |
Lookaround checks the surrounding text without including it in the match. \d+(?= dollars) finds 25 in pay 30 euros or 25 dollars. Many regex engines allow only fixed-length lookbehind. Java is more generous: (?<=\$), (?<=ab{1,3}) and even (?<=x.*) work in current JDKs, because unbounded quantifiers are given a very large internal maximum. A lookbehind whose length can't be computed at all, such as one containing a back-reference, is rejected with "Look-behind group does not have an obvious maximum length". Long lookbehinds are slow, so keep them short.
Unicode characters and code points
| Syntax | Matches |
|---|---|
\x{1F600} | the code point U+1F600, even though it takes two chars |
\u0041, \x41, \0101 | a UTF-16 code unit in hex or octal |
\t, \n, \r, \f, \a, \e | tab, newline, carriage return, form feed, alert, escape |
\cH | a control character (\cH is backspace) |
\N{GREEK SMALL LETTER ALPHA} | a character by its Unicode name (Java 9) |
\X | one extended grapheme cluster |
Patterns work on code points, so . matches a whole emoji, not half of a surrogate pair. But a letter followed by a combining accent is two code points, and . matches only the letter. \X matches what a reader sees as one character, and splitting on \b{g} breaks a string into such clusters.
The program
The demo tests many small patterns against sample inputs with matches (the whole string must match) and find (somewhere in the string), and shows the error you get for an invalid pattern. Article 37 explains these methods in detail.
import java.util.*;
import java.util.regex.*;
public class Solution {
static void test(String regex, String... inputs) {
Pattern p = Pattern.compile(regex);
var yes = new ArrayList<String>();
var no = new ArrayList<String>();
for (String s : inputs) (p.matcher(s).matches() ? yes : no).add(s);
System.out.printf("%-26s matches %s, not %s%n", regex, yes, no);
}
static void firstMatch(String regex, String input) {
Matcher m = Pattern.compile(regex).matcher(input);
System.out.printf("%-26s in %-22s finds %s%n", regex, '"' + input + '"',
m.find() ? "\"" + m.group() + "\"" : "nothing");
}
public static void main(String[] args) {
System.out.println("--- literals, dot, alternation ---");
test("[Jj]ava.+", "javanese", "Java", "Core Java");
test(".a.a", "Java", "data", "banana");
test("be+s?", "be", "bee", "bees", "bs");
test(".(oo|ee)f", "beef", "woof", "eef");
test(".oo|eef", "woo", "eef", "woof");
System.out.println("--- character classes ---");
test("[^0-9]+", "abc", "a1c");
test("[]^-]+", "]^-", "a");
test("[a-z&&[^aeiou]]+", "rhythm", "rhyme");
test("\\d{3}-\\d{4}", "555-1234", "55-12345");
test("\\p{Lu}\\p{Ll}+", "Zoë", "Émile", "anna");
test("\\p{IsGreek}+", "αβγ", "abc");
test("\\p{Sc}\\d+", "€20", "$5", "#5");
test("\\p{javaUpperCase}+", "ÄBC", "aBC");
System.out.println("--- quantifiers ---");
test("[1-9][0-9]*", "7", "42", "042");
test("[0-7]{1,3}", "7", "777", "7777", "8");
firstMatch("<.+>", "<b>bold</b> text");
firstMatch("<.+?>", "<b>bold</b> text");
test("'[^']*'", "'ok'", "'unclosed");
test("'[^']*+'", "'ok'", "'unclosed");
test("a*+a", "aaa"); // possessive: gives nothing back
System.out.println("--- groups and back-references ---");
test("(['\"]).*\\1", "'Fred'", "\"Fred\"", "\"Fred'");
test("(?<word>\\w+) \\k<word>", "hello hello", "hello world");
test("(?:ab)+", "ababab", "aba");
System.out.println("--- boundaries and lookaround ---");
firstMatch("\\bcat\\b", "concat cat catalog");
firstMatch("\\Bcat\\B", "concat cat locate");
firstMatch("\\d+(?= dollars)", "pay 30 euros or 25 dollars");
firstMatch("(?<=\\$)\\d+", "costs $40 now");
firstMatch("\\b\\w+\\b(?!\\.)", "end. start");
test("^Java$", "Java", "Java!");
System.out.println("--- escaping ---");
String price = "($0.99)";
test("\\(\\$0\\.99\\)", price);
test("\\Q($0.99)\\E", price);
test(Pattern.quote("a\\Eb"), "a\\Eb");
System.out.println("Pattern.quote(\"1+1\") = " + Pattern.quote("1+1"));
try {
Pattern.compile("(unclosed");
} catch (PatternSyntaxException e) {
System.out.println("PatternSyntaxException: " + e.getDescription() + " near index " + e.getIndex());
}
System.out.println("--- Unicode ---");
test("\\x{1F600}", "😀");
test(".", "😀", "é");
test("\\X", "😀", "é");
test("\\w+", "naïve");
test("(?U)\\w+", "naïve");
System.out.println("graphemes of \"é👍🏽!\": " + Arrays.toString("é👍🏽!".split("\\b{g}")));
}
}
--- literals, dot, alternation ---
[Jj]ava.+ matches [javanese], not [Java, Core Java]
.a.a matches [Java, data], not [banana]
be+s? matches [be, bee, bees], not [bs]
.(oo|ee)f matches [beef, woof], not [eef]
.oo|eef matches [woo, eef], not [woof]
--- character classes ---
[^0-9]+ matches [abc], not [a1c]
[]^-]+ matches []^-], not [a]
[a-z&&[^aeiou]]+ matches [rhythm], not [rhyme]
\d{3}-\d{4} matches [555-1234], not [55-12345]
\p{Lu}\p{Ll}+ matches [Zoë, Émile], not [anna]
\p{IsGreek}+ matches [αβγ], not [abc]
\p{Sc}\d+ matches [€20, $5], not [#5]
\p{javaUpperCase}+ matches [ÄBC], not [aBC]
--- quantifiers ---
[1-9][0-9]* matches [7, 42], not [042]
[0-7]{1,3} matches [7, 777], not [7777, 8]
<.+> in "<b>bold</b> text" finds "<b>bold</b>"
<.+?> in "<b>bold</b> text" finds "<b>"
'[^']*' matches ['ok'], not ['unclosed]
'[^']*+' matches ['ok'], not ['unclosed]
a*+a matches [], not [aaa]
--- groups and back-references ---
(['"]).*\1 matches ['Fred', "Fred"], not ["Fred']
(?<word>\w+) \k<word> matches [hello hello], not [hello world]
(?:ab)+ matches [ababab], not [aba]
--- boundaries and lookaround ---
\bcat\b in "concat cat catalog" finds "cat"
\Bcat\B in "concat cat locate" finds "cat"
\d+(?= dollars) in "pay 30 euros or 25 dollars" finds "25"
(?<=\$)\d+ in "costs $40 now" finds "40"
\b\w+\b(?!\.) in "end. start" finds "start"
^Java$ matches [Java], not [Java!]
--- escaping ---
\(\$0\.99\) matches [($0.99)], not []
\Q($0.99)\E matches [($0.99)], not []
\Qa\E\\E\Qb\E matches [a\Eb], not []
Pattern.quote("1+1") = \Q1+1\E
PatternSyntaxException: Unclosed group near index 9
--- Unicode ---
\x{1F600} matches [😀], not []
. matches [😀], not [é]
\X matches [😀, é], not []
\w+ matches [], not [naïve]
(?U)\w+ matches [naïve], not []
graphemes of "é👍🏽!": [é, 👍🏽, !]
A few things to check in the output:
.oo|eefdoesn't matchwoof. Alternation has the lowest precedence of all operators.- The greedy
<.+>spans two tags, while the reluctant<.+?>stops at the first>. a*+amatches nothing, since the possessive quantifier never gives back ana.Pattern.quoteescaped the embedded\Ecorrectly..matches a whole emoji but noteplus a combining accent, while\Xmatches both.
Common questions
Should I validate email addresses with a regex?
Only loosely. The full address syntax is far too complex for a sensible regex, and a "perfect" pattern still cannot tell whether the mailbox exists. A pattern like [^@\s]+@[^@\s]+\.[^@\s]+ catches typos; the real check is sending a confirmation email.
How do I match a whole word only?
Surround it with word boundaries: \bcat\b matches cat but not category. In a Java string literal that is "\\bcat\\b". For non-ASCII words, add the UNICODE_CHARACTER_CLASS flag so that \b knows which characters are letters.
Is Java's regex syntax the same as JavaScript's or Python's?
The core is the same: classes, quantifiers, groups, anchors. Differences show up in details such as named-group syntax (Python's re module writes (?P<name>...), Java (?<name>...)), possessive quantifiers (not in JavaScript), Unicode defaults and replacement syntax. Test patterns with Java itself, for example in jshell, rather than with an online tester set to another flavor.
How do I test a regex quickly?
jshell is ideal: "2026-11-14".matches("\\d{4}-\\d{2}-\\d{2}") gives an immediate answer. Online testers are handy if you select the Java flavor, and a few unit tests with matching and non-matching examples document a pattern for future readers.
Are regular expressions slow?
A compiled pattern applied to short strings is fast. Costs come from recompiling the same pattern repeatedly (as String.matches and String.split do with complex patterns), from catastrophic backtracking, and from using a regex where indexOf, startsWith or contains would do.
API reference
| API | Purpose |
|---|---|
Pattern.compile(regex) | compile a pattern; throws PatternSyntaxException if it's invalid |
Pattern.matches(regex, input) | one-off test that the whole input matches |
Pattern.quote(s) | a pattern that matches s literally |
PatternSyntaxException.getDescription(), getIndex(), getPattern() | details of a syntax error |
Character.UnicodeScript.forName, Character.UnicodeBlock.forName | the names accepted by \p{IsScript} and \p{InBlock} |
Summary
- Characters match themselves, except
. * + ? { } [ ] ( ) | \ ^ $, which you escape with\or\Q...\E. In Java source, every regex backslash is doubled. - Brackets define one-character classes with ranges, negation
[^...]and intersection&&.\d \w \sare ASCII-only unless you request Unicode semantics, and\p{...}selects Unicode categories, scripts, blocks and properties. - Quantifiers
? * + {m,n}are greedy by default. Add?for reluctant and+for possessive matching. - Parentheses capture. Back-references
\1and\k<name>match the same text again, and(?:...)groups without capturing. ^ $ \b \A \zand lookaround match positions. Keep lookbehinds short; back-references aren't allowed in them.- Avoid nested ambiguous quantifiers on untrusted input. They can backtrack exponentially.
Practice Questions
Write a regex for a time such as 9:05 or 12:59 on a 12-hour clock.
(1[0-2]|[1-9]):[0-5][0-9]. The hour is 1 to 9 or 10 to 12, and the minutes run from 00 to 59. As a Java string literal it needs no backslashes at all. To allow an optional am/pm, append \s?[ap]m (\\s?[ap]m in the literal).
What do \<.*\> and \<.*?\> match in the input \<a\>\<b\>, and how would a character class avoid the issue entirely?
The greedy <.*> matches the whole <a><b>, and the reluctant <.*?> matches <a>. <[^>]*> also matches <a>, without any backtracking, because the class can't run past a >.
Why doesn't \w+ match the word café by default, and what are two ways to fix it?
By default \w means [a-zA-Z0-9_], which doesn't include é. Either turn on Unicode classes with the flag Pattern.UNICODE_CHARACTER_CLASS or (?U) at the start of the pattern, or use explicit properties such as [\p{L}\p{M}\p{N}_]+.
What is the Java string literal for a regex that matches a Windows path separator followed by a dot?
The regex is \\\.: an escaped backslash, then an escaped dot. In a string literal each backslash doubles, giving "\\\\\\.". That's error-prone, so Pattern.quote("\\.") is a good alternative.
Explain why (a+)+b is slow on the input aaaaaaaaaaaaaaaaaaaaaaaac and how to fix it.
There's no b, so the match must fail. Before failing, the engine tries every way to split the run of as between the inner and outer +, and the number of splits grows exponentially with the length. a+b describes the same strings with only one way to match. Making the quantifier possessive, (a+)++b, or using an atomic group, (?>(a+)+)b, also prevents the backtracking.
Previous: Java Serialization: readResolve, writeReplace, Versioning and Security
Next: Java Regex Matching: matches, find, Groups and Named Groups
Related reading
- The Java Serialization File Format: Handles, Class Descriptors and Fingerprints
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Generics: Generic Classes and Generic Methods
- Throwing Exceptions and Creating Custom Exception Classes in Java

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.