Command Palette

Search for a command to run...

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

matches, find and the basic building blocks

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?

matches, find and the basic building blocks
Sign in to run this example in your browser.

Expected output

12345 matches \d+: true
abc123 matches \d+: false
found 66 at 6-8
found 3 at 20-21
lookingAt: true, matches: false
vowels starred: s*m*s* ch**
words: [chai, is, hot]
four-letter words: chai very
greedy:    <b>bold</b><i>it</i>
reluctant: <b>
negated:   <b>
possessive found: false