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
).
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
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".
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