/^(\w+?)_?(\d{0,2})(?:\[([^\[\]]*)\])?$/
(\w+?)
uses a non-greedy quantifier to capture the identifier part without any trailing _
.
_?
is greedy so will beat the +?
in the previous part.
(\d{0,2})
will capture 0-2 digits. It is greedy, so even if there is no _
between the identifier and digits, this will capture digits.
(?:...)?
makes the square bracketed section optional.
\[([^\[\]]*)\]
captures the contents of a square bracketed section that does not itself contain square brackets.
'some_param_0[name]'.match(/^(\w+?)_(\d{0,2})(?:\[([^\[\]]*)\])?$/)
produces an array like:
["some_param_0[name]", // The matched content in group 0.
"some_param", // The portion before the digits in group 1.
"0", // The digits in group 2.
"name"] // The contents of the [...] in group 3.
Note that the non-greedy quantifier might interact strangely with the bounded repetition in \d{0,2}
.
'x1234[y]'.match(/^(\w+?)_?(\d{0,2})(?:\[([^\[\]]*)\])?$/)
yields
["x1234[y]","x12","34","y"]