Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of the ampersand in regular expressions in Perl

Tags:

regex

perl

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 !) 
like image 638
ruggedbuteducated Avatar asked May 08 '13 01:05

ruggedbuteducated


People also ask

What does ampersand do in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself.

Does Ampersand need to be escaped in regex?

Thanks. @RandomCoder_01 actually, no escapes are needed. & is not a special regex character, so no need to escape it.

What does ?= * Mean in regex?

. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.


1 Answers

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.

like image 166
sidyll Avatar answered Sep 21 '22 04:09

sidyll