regex - Why can't I match a substring which may appear 0 or 1 time using /(subpattern)?/ -
the original string this:
checksession ok:6178 avg:479 avgnet:480 maxtime:18081 fail1:19
the last part "fail1:19" may appear 0 or 1 time. , tried match number after "fail1:", 19, using this:
($reg_suc, $reg_fail) = ($1, $2) if $line =~ /^checksession\s+ok:(\d+).*(fail1:(\d+))?/;
it doesn't work. $2 variable empty if "fail1:19" exist. if delete "?", can match if "fail1:19" part exists. $2 variable "fail1:19". if "fail1:19" part doesn't exist, $1 , $2 neither match. incorrect.
how can rewrite pattern capture 2 number correctly? means when "fail1:19" part exist, 2 numbers recorded, , when doesn't exit, number after "ok:" recorded.
first, number in fail
field end in $3
, variables filled according opening parentheses. second, codaddict shows, .*
construct in re hungry, eat fail...
part. third, can avoid numbered variables this:
my $line = "checksession ok:6178 avg:479 avgnet:480 maxtime:18081 fail1:19"; if(my ($reg_suc, $reg_fail, $addend) = $line =~ /^checksession\s+ok:(\d+).*?(fail1:(\d+))?$/ ) { warn "$reg_suc\n$reg_fail\n$addend\n"; }
Comments
Post a Comment