Command Palette

Search for a command to run...

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

Flags, validation and streams of matches

asMatchPredicate() (Java 11) requires a whole-string match, like matches(). The commented pattern is a text block, so this example needs Java 15.

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?

Flags, validation and streams of matches Java 15+
Sign in to run this example in your browser.

Expected output

errors: [disk full, timeout]
dot without DOTALL: false
dot with (?s): true
case-insensitive (?i): true
411001 is a PIN: true
41100 is a PIN: false
4110011 is a PIN: false
41100a is a PIN: false
commented pattern: 555 / 1234