Command Palette

Search for a command to run...

Back to the lesson: Topic 6.7 — Regular Expressions
Core Java · Example 2 of 3 Java 9+

Groups, named groups, backreferences and replacements

replaceAll(Function) and results() arrived in Java 9; named groups in Java 7.

A regular expression (regex) is a small pattern language for describing text, such as "three digits, a dash, four digits". Java's java.util.regex package compiles a pattern once (Pattern) and uses it to test, search, extract and replace text (Matcher), and String.matches, split and replaceAll use it too.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static boolean isValidUsername(String s): 3 to 16 characters, starting with a letter, then letters, digits or underscores. Test "asha_92", "9lives", "ab" and "ravi.k".

02

Extract every hashtag (a # followed by word characters) from "Loving #chai and #samosa at #Pune2026!" and print them as a list.

03

Collapse runs of whitespace in "too many \t spaces" into single spaces and print the result in square brackets.

Explain it without notes

01

What's the difference between matches(), find() and lookingAt()?

02

Why must you write "\\d" in Java source to mean the regex \d?

03

Explain greedy, reluctant and possessive quantifiers with an example.

04

What is ReDoS, how would you detect it, and how do you defend against it?

05

Why should a Pattern be stored in a static final field, and can it be shared between threads?

Groups, named groups, backreferences and replacements Java 9+
Sign in to run this example in your browser.

Expected output

year 2026, month 10, day 04
year 2026, month 10, day 09
reordered: 04/10/2026
user ravi.k, domain hectal.in
masked: ***@hectal.in
repeated word: is
repeated word: test
literal split: 1 | 1=2
safe replacement: cost: $5
function replace: CHAI and more CHAI
match count: 4