Lisa
Lisa

Reputation: 959

Optionality and "or" in capturing groups in perl

I want to get a capturing group in a regex that has several "or"s and an optional group. This my my regex: (a|e|i|o|u)?(a|e|i|o|u)(g|k) I want it to find one or two vowels before a g or a k - like "taek" and "tag".

I tried putting parenthesis around (a|e|i|o|u)?(a|e|i|o|u) but $1 is still uninitialized.

Upvotes: 2

Views: 175

Answers (1)

Jim Driscoll
Jim Driscoll

Reputation: 904

$1 will be unset if the optional first capture doesn't match anything; that doesn't imply that $2 is unset. If you want $1 to be empty instead, you need to wrap the brackets around it, i.e. ([aeiou]?). In if you really needed to use alternation and the optional indicator then you would need two levels of brackets, and for that case you'd probably want to turn capturing off for the inner one with "?:", i.e. ((?:a|e|i|o|u)?).

Upvotes: 2

Related Questions