Standard libraries
libs2RegexPattern
- Path
- pkg13libs/libs2RegexPattern.java
- Package
- pkg13libs
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg13libs/libs2RegexPattern.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg13libs;2 3import java.util.regex.Matcher;4import java.util.regex.Pattern;5 6/*7 * libs2RegexPattern.java8 * ----------------------9 * Regular expressions with java.util.regex (Pattern + Matcher).10 *11 * DEFINITION:12 * A regex is a pattern that describes a set of strings. Pattern compiles it;13 * Matcher applies it to input to test, find, extract groups, or replace.14 *15 * KEY POINTS:16 * - Compile a Pattern once and reuse it (compilation is not free).17 * - matches() = whole string; find() = next match anywhere; group(n) = captures.18 * - Use named groups (?<name>...) for readability.19 * - String.matches/replaceAll are handy shortcuts for one-off uses.20 */21public class libs2RegexPattern {22 23 public static void main(String[] args) {24 // 1) Validate with a full match25 Pattern email = Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[a-z]{2,}$");26 for (String s : new String[]{"[email protected]", "not-an-email"})27 System.out.printf("%-15s valid email? %s%n", s, email.matcher(s).matches());28 29 // 2) Find all matches30 System.out.println("\nNumbers found:");31 Matcher m = Pattern.compile("\\d+").matcher("order 12, item 345, qty 6");32 while (m.find()) System.out.println(" " + m.group() + " at index " + m.start());33 34 // 3) Capture groups (named) — parse a date35 Pattern date = Pattern.compile("(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})");36 Matcher dm = date.matcher("Release: 2026-06-14");37 if (dm.find())38 System.out.printf("%nParsed date: year=%s month=%s day=%s%n",39 dm.group("y"), dm.group("m"), dm.group("d"));40 41 // 4) Replace using backreferences42 String masked = "card 4111 1111 1111 1234".replaceAll("\\d{4}(?= \\d{4})", "****");43 System.out.println("\nMasked: " + masked);44 45 // 5) Split on a regex46 System.out.println("\nSplit: " + java.util.Arrays.toString("a, b ,c , d".split("\\s*,\\s*")));47 }48}