Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex with exclamation marks

Tags:

regex

perl

How do you define/explain this Perl regex:

$para =~ s!//!/!g;

I know the s means search, and g means global (search), but not sure how the exclamation marks ! and extra slashes / fit in (as I thought the pattern would look more like s/abc/def/g).

like image 663
kurotsuki Avatar asked Feb 16 '12 03:02

kurotsuki


2 Answers

Perl's regex operators s, m and tr ( thought it's not really a regex operator ) allow you to use any symbol as your delimiter.

What this means is that you don't have to use / you could use, like in your question !

# the regex
s!//!/!g

means search and replace all instances of '//' with '/'

you could write the same thing as

s/\/\//\/g 

or

s#//#/#g

or

s{//}{/}g

if you really wanted but as you can see the first one, with all the backslashes, is very hard to understand and much more cumbersome.

More information can be found in the perldoc's perlre

like image 74
zellio Avatar answered Nov 02 '22 22:11

zellio


The substitution regex (and other regex operators, like m///) can take any punctuation character as delimiter. This saves you the trouble of escaping meta characters inside the regex.

If you want to replace slashes, it would be awkward to write:

s/\/\//\//g;

Which is why you can write

s!//!/!g; 

...instead. See http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators

And no, s/// is the substitution. m/// is the search, though I do believe the intended mnemonic is "match".

like image 36
TLP Avatar answered Nov 02 '22 22:11

TLP