Course contentsShow
← Java
Lesson 2319 of 2,87044. Regular ExpressionsFree lesson

Other Useful Flags: UNICODE_CASE and COMMENTS

Explore UNICODE_CASE for full Unicode support and COMMENTS mode for whitespace and documentation in patterns.

Other Useful Flags: UNICODE_CASE and COMMENTS

You'll learn how to enable full Unicode case-insensitive matching and document complex patterns with inline comments.

The UNICODE_CASE Flag

By default, Java's CASE_INSENSITIVE flag only handles ASCII characters properly. When working with international text containing accented characters, Cyrillic, Greek, or other Unicode scripts, you need Pattern.UNICODE_CASE.

This flag ensures that case-insensitive matching respects Unicode case-folding rules across all languages. It's typically combined with CASE_INSENSITIVE:

Pattern pattern = Pattern.compile("café", 
    Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcher = pattern.matcher("CAFÉ");
System.out.println(matcher.matches()); // true

Without UNICODE_CASE, characters like "é" and "É" might not match correctly. The inline flag equivalent is (?iu).

The COMMENTS Flag

Complex regular expressions quickly become unreadable. The Pattern.COMMENTS flag (inline: (?x)) lets you add whitespace and comments to your patterns, making them self-documenting:

String emailPattern = """
    (?x)              # Enable comments mode
    [a-z0-9]+         # Local part: letters and digits
    @                 # Literal @ symbol
    [a-z0-9]+         # Domain name
    \\.               # Literal dot
    [a-z]{2,}         # Top-level domain
    """;

Pattern pattern = Pattern.compile(emailPattern);

In COMMENTS mode, whitespace is ignored (use \s or [ ] for literal spaces), and # starts a comment until the end of the line. Think of it like adding inline documentation to your regex.

Key Takeaway:
Use UNICODE_CASE with CASE_INSENSITIVE for proper international text matching, and use COMMENTS mode to make complex patterns readable with whitespace and inline documentation.