dwilbank
dwilbank

Reputation: 2520

use of the ampersand here means pre_match?

What is the ampersand doing in the code below?

s.reverse.gsub( /\d{3}(?=\d)/, '\&,' ).reverse

One would think, after attempting to look up such things, that it is a special variable meaning post_match or pre_match, but the docs say nothing about ampersands - only dollar signs either followed by or preceded by a tick mark.

Upvotes: 0

Views: 136

Answers (1)

Sabuj Hassan
Sabuj Hassan

Reputation: 39385

\& defines the whole string that is matched by the regex. see this simplified example:

s = "p1:1 1:1";
print s.gsub( /[a-z]/, '[\&],' ) ## only p is matched

output: [p],1:1 1:1

Similarly, the \1 defines the first group that is matched from the regex. (Similar goes for \2,\3... so on). An example:

s = "p1:1 1:1";
print s.gsub( /(\d:\d)/, '[\1]' )

output: p[1:1] [1:1]

Upvotes: 1

Related Questions