Guys I have this regular expression in Perl which I don't understand.
s/\w+$/($`!)$&/;
The original string was
"huge dinosaur"
After that regular expression is executed, the string is now:
"huge (huge !)dinosaur"
I quite dont understand how that happened. And I don't understand what the ampersand is doing there. I understand the $`, but why is it that it's there, from what i know the $` takes the value before the match, which is i think nothing because there is no matching expression before the that regular expression above.
If somebody can link me to some very helpful tutorial on regular expressions on Perl is really appreciated.
Thanks
EDIT: I understand now what the ampersand means, it saves the match and the $` saves the value before the match, Now what i dont understand again is this whole part:
($`!)$&
how did this part became
(huge !)
Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself.
Thanks. @RandomCoder_01 actually, no escapes are needed. & is not a special regex character, so no need to escape it.
. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.
You're correct, $`
is a special variable which holds the contents before the match. $&
is similar, but holds what was matched and $'
holds what was after the match.
In "huge dinosaur"
, /\w+$/
matches dinosaur
. So the variable contents are:
$` => "huge " $& => "dinosaur" $' => ""
Note that what was matched is dinosaur
. Then it's replacing the dinosaur
portion of the string with an opening parens, "huge "
, exclamation mark, closing parens and finally dinosaur
(what was matched).
Check the Perl documentation for perlvar
and perlre
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With