Skillversitas

Regular Expressions

A Regular Expression (Regex) is a string pattern used for matching, searching, and manipulating text. Java provides the Pattern and Matcher classes from the java.util.regex package for working with regexes. Regexes are very powerful for input validation, pattern searching, and text parsing.

Pattern.compile() compiles a regex into a Pattern object. Pattern.matcher() creates a Matcher object that can search the target string. Matcher.find() finds the next occurrence, Matcher.group() returns the match, and Matcher.replaceAll() replaces all matches.

Java 11+ supports String.matches() and String.replaceAll(), which use regexes directly. Named groups (?<name>...) make it easy to retrieve match results by name.

Regex Metacharacters:

Character Description Example
. Any character a.c matches "abc", "aXc"
\d Digit (0-9) \d+ matches "123"
\w Letter/digit/underscore \w+ matches "hello_123"
\s Whitespace \s+ matches " " or a tab
* 0 or more ab* matches "a", "abbb"
+ 1 or more ab+ matches "ab", "abbb"
? 0 or 1 ab? matches "a", "ab"
{n,m} n to m times \d{3,5} matches 3-5 digits
[abc] One of a/b/c [aeiou] matches a vowel
^...$ Start/end of string ^Hello$ matches "Hello"

Code Example

import java.util.regex.*;

public class RegexJava {
    public static void main(String[] args) {
        // Email validation
        String email = "[email protected]";
        boolean valid = email.matches("^[\\w.-]+@[\\w.-]+\\.\\w{2,}$");
        System.out.println("Email valid: " + valid);

        // Pattern search
        String text = "Today is July 13, 2026, tomorrow is July 14, 2026";
        Pattern p = Pattern.compile("\\d{1,2}\\s+\\w+\\s+\\d{4}");
        Matcher m = p.matcher(text);
        while (m.find()) {
            System.out.println("Found: " + m.group());
        }

        // ReplaceAll
        String noTelp = "0812-3456-7890";
        String clean = noTelp.replaceAll("[^0-9]", "");
        System.out.println("Cleaned: " + clean);

        // Named groups
        String log = "2026-07-13 14:30:00 ERROR Connection failed";
        Pattern logP = Pattern.compile(
            "(?(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) " +
            "(?<level>\\w+) (?<message>.*)");
        Matcher logM = logP.matcher(log);
        if (logM.matches()) {
            System.out.println("Time: " + logM.group("time"));
            System.out.println("Level: " + logM.group("level"));
            System.out.println("Message: " + logM.group("message"));
        }
    }
}

Code Explanation

  1. email.matches(regex) returns true if the entire string matches the pattern. ^ and $ ensure matching from start to end.
  2. Pattern.compile() compiles the regex once for performance. Matcher.find() finds the next match — loop while matches remain.
  3. replaceAll("[^0-9]", "") removes all non-digit characters.
  4. Named groups (?(?<time>...) make it easy to retrieve match results by name without counting groups.

Everyday Example

An online registration form validation program:

import java.util.regex.Pattern;

public class FormValidation {
    static boolean validEmail(String email) {
        return email.matches("^[\\w.-]+@[\\w.-]+\\.\\w{2,}$");
    }

    static boolean validNoHP(String no) {
        return no.matches("^\\+?62[0-9]{9,13}$");
    }

    static boolean validPassword(String pw) {
        // Minimum 8 characters, with an uppercase, a lowercase, and a digit
        return pw.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$");
    }

    public static void main(String[] args) {
        System.out.println("Email valid: " + validEmail("[email protected]"));
        System.out.println("No HP valid: " + validNoHP("+62812345678"));
        System.out.println("Pass valid: " + validPassword("John1234"));
        System.out.println("Weak password: " + validPassword("john1234"));
    }
}

Summary

Regex is a powerful tool for text manipulation in Java. Pattern and Matcher provide a complete API for searching and replacing patterns. Use named groups for complex regexes, and compile the Pattern once if it is reused, for optimal performance.