yo2048
yo2048

Reputation: 25

Perl regular expression replacement

The code is here. My question is since $1 is Fred and this is a replacement, which means replacing fred or barney with Fred, why cannot the answer be like I saw FRED with FRED. i have no idea for what's going on here. Thank you for your answer!

$_ = "I saw Barney with Fred.";
s/(fred|barney)/\U$1/gi; # $_ is now "I saw BARNEY with FRED."

Upvotes: 1

Views: 76

Answers (2)

tripleee
tripleee

Reputation: 189317

$1 refers to "whatever the first capturing group captured". So when (fred|barney) matches fred, that's what $1 contains, but when it matches barney, that is then what $1 contains.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Because the capturing group not only captures the string Fred but also Barney. So if the regex engine see Fred, it replaces immediately with Uppercase FRED and if the engine sees Barney, it replaces it with Uppercase Barney.

Upvotes: 1

Related Questions