简体   繁体   中英

What's the difference between tr/// and s/// when using regex in Perl?

I was wondering when one should use s/// over tr/// when working with regular expressions in Perl?

s/// is for substitution:

$string =~ s/abc/123/;

This will replace the first "abc" found in $string with "123".

tr/// is for transliteration:

$string =~ tr/abc/123/;

This will replace all occurrences of "a" within $string with "1", all occurrences of "b" with "2", and all occurrences of "c" with "3".

tr/// is not a regular expression operator. It is suitable (and faster than s/// ) for substitutions of one single character with another single character, or (with the d modifier) substituting a single character with zero characters.

s/// should be used for anything more complicated than the narrow use cases of tr .

From perlop: Quote and Quote-like Operators

Note that tr does not do regular expression character classes such as \\d or [:lower:]. The tr operator is not equivalent to the tr(1) utility. If you want to map strings between lower/upper cases, see lc and uc, and in general consider using the s operator if you need regular expressions.

To add to the above answers, if you are using utf8 character set, go with s instead of tr even for single characters

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