I’m writing a Perl regex to match both the strings x bla and [x] bla. One alternative is /(?:x|\[x\]) bla/. This isn’t desirable, because in the real world, x is more complicated, so I want to avoid repeating it.
The best solution so far is putting x in a variable and pre-compiling the regex:
my $x = 'x';
my $re = qr/(?:$x|\[$x\]) bla/o;
Is there a neater solution? In this case, readability is more important than performance.
It’s possible, but not all that clean. You can use the fact that conditional subpatterns support tests such as
(?(N))to check that the Nth capturing subpattern successfully matched. So you can use an expression such as/(\[)?X(?(1)\])/to match ‘[X]’ or ‘X’.