Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: regex doubt on excluding

by kcott (Archbishop)
on Apr 22, 2014 at 02:31 UTC ( [id://1083100]=note: print w/replies, xml ) Need Help??


in reply to regex doubt on excluding

If you look in "perlre: Metacharacters", you'll see that '$' matches "the end of the line (or before newline at the end)" (emphasis added). So, what you really want is to match any whitespace character except if it follows '$'. That makes your substitution "s/(?<!$)\s//gm", shown here:

#!/usr/bin/env perl -l use strict; use warnings; my $string = "\t is a TAB\n is a SPACE\nTAB\t and SPACE"; print '*** BEFORE ***'; print $string; $string =~ s/(?<!$)\s//gm; print '*** AFTER ***'; print $string;

Output:

*** BEFORE *** is a TAB is a SPACE TAB and SPACE *** AFTER *** isaTAB isaSPACE TABandSPACE

However, if you know that you only want to match the whitespace characters space (" ") and tab ("\t"), then the transliteration "y/\t //d" will be faster. (See "Search and replace or tr" in "Perl Performance and Optimization Techniques" for a Benchmark example.) As you can see, the code is virtually identical (which makes replacing the s/// with y/// easy):

#!/usr/bin/env perl -l use strict; use warnings; my $string = "\t is a TAB\n is a SPACE\nTAB\t and SPACE"; print '*** BEFORE ***'; print $string; $string =~ y/\t //d; print '*** AFTER ***'; print $string;

Output:

*** BEFORE *** is a TAB is a SPACE TAB and SPACE *** AFTER *** isaTAB isaSPACE TABandSPACE

[In case you didn't know, y/// and tr/// are synonymous. You'll find both forms used in different sections of the perlop documentation.]

-- Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1083100]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-26 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found