Regex Comments Mode Readable Patterns

Compile regex with Pattern.COMMENTS so whitespace and # comments become layout, keeping literal spaces via bracketed [ ] when needed.

JavaCli Tooling

Code

snippet
import java.util.regex.Pattern;

public class ReadableRegex {

    public static void main(String[] args) {
        // Pattern.COMMENTS(内联写法 (?x)):空白与 # 注释被忽略,正则可排版成可读形式
        Pattern email = Pattern.compile("""
                ^[\\w.+-]+      # local part
                @               # at sign
                [\\w-]+         # domain label
                (\\.[\\w-]+)+   # dot-separated suffix chain
                $               # end
                """, Pattern.COMMENTS);

        for (String input : new String[] {"[email protected]", "[email protected]"}) {
            System.out.println(input + " -> " + email.matcher(input).matches());
        }

        // 字面空白要写成 [ ](或 \\Q...\\E、\\ 转义),否则会被当作排版忽略
        Pattern spaced = Pattern.compile("a[ ]b");
        System.out.println("a b -> " + spaced.matcher("a b").matches());
        System.out.println("ab  -> " + spaced.matcher("ab").matches());
    }
}

Regex Comments Mode Readable Patterns: how the code works

The working surface is the class ReadableRegex and the function main — everything else is wiring.

One loop does the cycling here: for (String input : new String[] {"[email protected]", "[email protected]"}).

Caveats

  • Behavior traces entirely to the standard library — no external surface.

Putting it to use

The function shape: public static void main(String[] args)

Output lines are prefixed (a b ->, ab ->); every printed line points back to the step that made it.

Core lines

(\\.[\\w-]+)+   # dot-separated suffix chain
$               # end
""", Pattern.COMMENTS);
Pattern spaced = Pattern.compile("a[ ]b");

Interactive Tools for This Topic

FAQ

What does Regex Comments Mode Readable Patterns print when run?
Run it as a complete program — the output lines carry labels such as `a b ->`, `ab ->`.