在perl中捕获组的可选性和“或”。

时间:2022-06-05 12:15:52

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".

我希望在regex中获得一个捕获组,该组具有多个“或”和一个可选组。这是我的regex:(|e|i|o|u)?(|e|i|o|u)(g|k)我想让它在g或k之前找到一两个元音,比如“taek”和“tag”。

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

我尝试将括号括起来(|e| I |o|u)?(|e| I |o|u)但$1仍未初始化。

1 个解决方案

#1


2  

$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)?).

如果可选的第一次捕获与任何内容不匹配,则$1将被取消设置;这并不意味着2美元是未设定的。如果您想要$1为空,则需要将括号括起来,即([aeiou]?)如果您真的需要使用交替和可选指示器,那么您将需要两个级别的括号,在这种情况下,您可能想要关闭用于内部的括号”?:“,即((?:我| | | e o | u)吗?)。

#1


2  

$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)?).

如果可选的第一次捕获与任何内容不匹配,则$1将被取消设置;这并不意味着2美元是未设定的。如果您想要$1为空,则需要将括号括起来,即([aeiou]?)如果您真的需要使用交替和可选指示器,那么您将需要两个级别的括号,在这种情况下,您可能想要关闭用于内部的括号”?:“,即((?:我| | | e o | u)吗?)。