Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How do I use regex to strip out specific characters in a string?

by Cubes (Pilgrim)
on Aug 23, 2001 at 00:15 UTC ( [id://107120]=note: print w/replies, xml ) Need Help??


in reply to How do I use regex to strip out specific characters in a string?

How about approaching from a slightly different angle: grab the bits of info you do want from the string, then use them to construct a new string.

Do a regex match on your initial string, using parens and array context to get back the pieces you're interested in, like so:

($month, $day, $hour, $min, $ampm) = ($stamp =~ m|(\d+)/(\d+)/\d+\s+(\ +d+):(\d+)(\w)|);
Then use those pieces to build your new string:
$newstamp = sprintf("%02d_%02d_%02d%02d%s", $month, $day, $hour, $min, + $ampm);
(Using %02d in sprintf will give you leading zeros in front of single digit numbers, which will make your resulting string more consistent -- change them to just %d to leave off the leading zeros)

This has the added benefit of making the code's function much more obvious 6 months from now than a cryptic series of substitutions, and being easier to update if and when your formats change.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-09-17 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The PerlMonks site front end has:





    Results (22 votes). Check out past polls.

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.