in reply to Regex dynamics
Taking just the [] part into consideration, what you want to match is going to be zero or more (one or more?): of either a series of other characters or a [...] pair. So at first blush, something like this:
But (as that regex itself shows) the something in brackets itself could be a little complicated to parse.m/\[ # initial [ (?: [^][]+ # non-bracket parts | \[somethinginbrackets\] # something in brackets )* # repeated \] # final ] /x
First, note that if you allow interpolated variables in your regex, the problem is a lot more complicated. $foo[bar] in a regex could be either the scalar $foo followed by a character class, or an interpolated array element. Perl uses a guessing function that gives different weights to characters found in the "bar" part to decide which (and doesn't always get it "right"). If "bar" is an array index, it will be arbitrary perl code. See "Gory details of parsing quoted constructs" in perlop for how to locate the ending ]. Also, you need to allow for interpolated aribitrary code: @{[foo(),"]"]}. That's not a matter of matching square brackets; the gory details rules will help find the ending "}".
Assuming you don't need to handle interpolation in the regex, you still have to deal with []], [x[:alnum:]y] (vs. [x[:alnum]), [[\]], and similar. See "Version 8 Regular Expressions" and the POSIX character class sections in perlre. (Update: previous sentence unmangled.)
Update: all things considered, you'd do yourself a great favor requiring your value to be quoted with "" or something else (with literal " in the value requiring a backslash) when the value has a ]. Or just require all brackets in the value to be backslashed. Then it's just a matter of matching m/\[ (?: [^][]+ | \\. )* \]/x.
Update: ++halley; I'm going to look at Text::Balanced.
|
|---|