in reply to How do I use regex to strip out specific characters in a 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:
Then use those pieces to build your new string:($month, $day, $hour, $min, $ampm) = ($stamp =~ m|(\d+)/(\d+)/\d+\s+(\ +d+):(\d+)(\w)|);
(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)$newstamp = sprintf("%02d_%02d_%02d%02d%s", $month, $day, $hour, $min, + $ampm);
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.
|
|---|