← Java from Scratch
Lesson 85 of 88 · 10 XP
Regular expressions
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A regular expression (RegEx) is a pattern for searching text:
| pattern | means |
|---|---|
\d |
a digit; \w — a letter/digit/_; \s — a whitespace character |
. |
any character |
[a-z], [^0-9] |
one of / none of |
+, *, ?, {2,4} |
1+, 0+, 0–1, from 2 to 4 times |
^, $ |
the start / the end of the line |
( ) |
a group — it can be extracted separately |
In a Java string the backslash is doubled: "\\d+".
import java.util.regex.*;
"2026-11-05".matches("\\d{4}-\\d{2}-\\d{2}") // true — the WHOLE string matches the pattern
"a1b22c333".replaceAll("\\d+", "#") // a#b#c#
"a, b;c".split("[,;]\\s*") // [a, b, c]
Matcher m = Pattern.compile("(\\w+)@(\\w+)\\.com").matcher(text);
while (m.find()) // all the matches in turn
System.out.println(m.group(1) + " at " + m.group(2));
Task. Read the whole text. Print: all the email addresses of the form name@domain.tld (the name is letters, digits,
a dot, _, -; the domain is letters, digits, -; the TLD is 2+ Latin letters) in order, separated by spaces (if there are none —
-); the sum of all the integers in the text that aren't part of addresses; and the text with every run of
whitespace replaced by a single space.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.