Regex Comments Mode Readable Patterns
Compile regex with Pattern.COMMENTS so whitespace and # comments become layout, keeping literal spaces via bracketed [ ] when needed.
Code
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
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
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 ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.