3

Is it possible with regex to repeat a captured group an amount of times with the added restriction that the amount to repeat is also found in a capture group?

Example:

Regex: /(a)([0-9])/g
String: ba1na3na2
Expected result: banaaanaa

I have never seen anything that does this, but maybe I have been looking in the wrong places. Note: I am using Perl - but I am interested to see answers for other flavours as well.

4

1 回答 1

5

在 perl 中,这个正则表达式会给你预期的结果,你的正则表达式是匹配的,而s正则表达式是一个替换:

s/(a)([0-9])/$1 x $2/eg;

像这样:

my $str = 'ba1na3na2';
$str =~ s/(a)([0-9])/$1 x $2/eg;
print $str;

香蕉

  • 修饰符将e右侧计算为表达式。
  • x操作员重复字符串。

更新:

正如@AvinashRaj 所说,这可能s/(a)([0-9]+)/$1 x $2/eg;更合适。取决于你是否想 ba20nana成为

  • 芭娜娜

或者

  • 啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
于 2016-02-26T08:57:53.163 回答