简体   繁体   中英

Perl regex with exclamation marks

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

The exclamation marks are the delimiter; perl lets you choose any character you want, within reason. The statement is equivalent to the (much uglier) s/\\/\\//\\//g — that is, it replaces // with / .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM