fastryan
fastryan

Reputation: 173

Regexp repetition defined by backreference

In Ruby (PCRE), is it possible to use a backreference to a captured decimal value to define a repetition length?

/^(\d+),.{\1}/.match('4,abcdefgh') # Should match '4,abcd'

The above code just returns nil (finds no matches).

Upvotes: 2

Views: 188

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110665

You could use two regular expressions:

str = '4,abcdefgh'

str =~ /\A(\d+,)/
str[0,$1.size+$1.to_i]
  #=> "4,abcd"     

Upvotes: 0

Stefan
Stefan

Reputation: 114138

No, you can't do that with regular expressions. If the range of decimal values however is limited, you could build a regular expression containing all possible combinations, something like:

'1abcde2abcde3abcde4abcde'.scan(/1.{1}|2.{2}|3.{3}|4.{4}/)
#=> ["1a", "2ab", "3abc", "4abcd"]

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36101

You can use String#to_i, which gives you the number at the start:

str = '4,abcdefgh'
str.match(/^(\d+),.{#{str.to_i}}/) # => #<MatchData "4,abcd" 1:"4">

Upvotes: 2

Related Questions