Featured post
regex - Removing delimiters from a date/time string -
i want take this
code: 2010-12-21 20:00:00
and make this:
code: 20101221200000
this last thing tried
code: #!/usr/bin/perl -w use strict; ($teststring) = '2010-12-21 20:00:00'; $result = " "; print "$teststring\n"; $teststring =~ "/(d\{4\})(d\{3\})(d\{3\})(d\{3\})(d\{3\})(d\{3\})/$result"; { print "$_\n"; print "$result\n"; print "$teststring\n"; }
and produced this:
code: nathan@debian:~/desktop$ ./ptest 2010-12-21 20:00:00 use of uninitialized value $_ in concatenation (.) or string @ ./ptest line 8. 2010-12-21 20:00:00 nathan@debian:~/desktop$
-thanks
first, here problem code:
$teststring =~ "/(d\{4\})(d\{3\})(d\{3\})(d\{3\})(d\{3\})(d\{3\})/$result";
you want use =~
substitution operator s///
. is, right hand side should not plain string, s/pattern/replacement/
.
in pattern part, \d
denote digit. however, \d
includes sorts characters in unicode digit class, safer use character class [0-9]
if that's want match against. [0-9]{4}
mean match characters 0
through 9
4 times. note should not escape curly brackets {
, }
.
the parentheses (
, )
define capture groups. in replacement part, want keep stuff captured, , ignore stuff did not.
in addition, assuming these timestamps occur in other input, , not want accidentally replace stuff did not mean (by blindly removing non-digits).
below, use /x
modifier s///
operator can format pattern
more using white-space.
#!/usr/bin/perl use strict; use warnings; while ( <data> ) { s{ ^ ([0-9]{4})- ([0-9]{2})- ([0-9]{2})[ ] ([0-9]{2}): ([0-9]{2}): ([0-9]{2}) }{$1$2$3$4$5$6}x; print; } __data__ code: 2010-12-21 20:00:00
or, using named capture groups introduced in 5.10
can make whole thing more readable:
#!/usr/bin/perl use 5.010; while ( <data> ) { s{ ^ ( ?<year> [0-9]{4} ) - ( ?<month> [0-9]{2} ) - ( ?<day> [0-9]{2} ) [ ] ( ?<hour> [0-9]{2} ) : ( ?<min> [0-9]{2} ) : ( ?<sec> [0-9]{2} ) } { local $"; "@+{qw(year month day hour min sec)}" }ex; print; } __data__ code: 2010-12-21 20:00:00
- Get link
- X
- Other Apps
Comments
Post a Comment