in reply to Help with a more precise regex

First. Your regexp is slightly wrong. It matches even strings like 'hello there 1d'. You would need one more (?:...) around the whole regexp except the ^ and $ to fix it. Currently the first alternative matches only at the start of the string, while the second only at the end. You want them to only match the whole string.

Anyway I would suggest something like this:

while (<STDIN>) { chomp; if ($_ and /^(?:(\d+)d)?(?:\s*(\d+)h)?$/i) { print "Days: $1, Hours: $2\n"; } else { print "Doesn't match\n"; } }
The $_ and ... is necessary to prevent an empty string from matching, the rest is taken care of by the regexp.

Jenda
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
   -- Rick Osborne

Edit by castaway: Closed small tag in signature

Replies are listed 'Best First'.
Re:^2 Help with a more precise regex
by LogicalChaos (Beadle) on Apr 25, 2003 at 20:25 UTC
    Hey Jenda,

    This is the one I was looking for. Pointing out the relative stupidity of my regex. I was checking for empty string, but then lost the fact that I didn't need to require the 'd' or 'h' portion, thus allowing for the deletion of the '|'. And at one point, I did correctly have the ^(?:...)$ wrapping the entire match, but lost it in one of my incantations.

    So, the final form I've chosen is:
    if ( $value and $value !~ /^(?:(\d+)d)?(?:\s*(\d+)h)?$/i ) { $result = "Please only enter time in one of these three formats: ' +3d', '4d 3h', '22h'"; } else { $day = $1 || 0; $hour = $2 || 0; }
    And it seems to work!

    Thanks,
    LogicalChaos