(?#…) and # — comments inside a pattern¶
One line: (?#text) is a comment group, ignored by the engine, in Python, Perl, PCRE2, Ruby and fancy-regex; under free-spacing mode (?x), everything from # to the end of the line is a comment in Python, Perl, Ruby, Java and Rust; and JavaScript, Java and Go have no (?#…) at all.
Level: reference · one construct, eight engines
What it means¶
Two mechanisms, and the second is the useful one:
(?#…)— an inline comment anywhere, no flag needed, cannot contain).#under(?x)— a line comment, which is how a forty-character pattern becomes a readable block:
The x mode also ignores whitespace, so a literal space has to be \ or [ ].
Measured¶
Verified output of kw_comment_sh.sh — regenerated by tools/run_examples.py, never hand-typed.
construct python perl node ruby java go rust fancy
(?#...) ab ab - ab - - - ab
hash under (?x) a a - a a - a a
hash without (?x) a#b a#b a#b a#b a#b a#b a#b a#b
Reading the table¶
- Row 1,
a(?#note)b. Python, Perl, Ruby andfancy-regexskip the comment and matchab. JavaScript, Java, Go and Rust'sregexrefuse it. - Row 2,
(?x)a#comment. Under free-spacing,#commentis ignored to the end of the row, so the pattern isaand the match isa— in Python, Perl, Ruby, Java and Rust. JavaScript has nox; Go has nox. - Row 3,
a#bwith no flag. A#is an ordinary character everywhere: all eight matcha#b. Turning on(?x)later would turn that#into a comment and silently truncate the pattern — the one way this feature bites.
The trap¶
Adding (?x) to an existing pattern. Every space in it disappears and every # starts a comment, so [a-z ]+#tag becomes [a-z]+. The mode is worth using from the start of a long pattern; it is dangerous to add afterwards.
Where it is measured in depth¶
- Flags, and where you can turn one on —
(?x)per engine and Perl'sxx.
See also¶
- Inline flags.
- Named group · Conditional —
(?(DEFINE)…)under(?x)is how a large PCRE2 pattern stays readable. - Readable patterns.