in reply to Filtering CGI Input

Your regexp is matching anything that has the literal string "0-9" in it. And then the !~ negates that match. Thus, since anything you've tried probably does not include the literal string "0-9" somewhere in it, the full expression is always true.

You want to match a character class - e.g., \d matches all digits, thus using /\d/ is a bit closer. What this does is match any digit, anywhere in the string.

You actually want to match 1 to 5 digits. So you can use the {} modifier: /\d{1,5}/. This matches anywhere from 1 to 5 digits, anywhere in the string. But that still matches "a1b" since it has somewhere between 1 and 5 digits. So you want to anchor the match to both the beginning and the end. And thus we get /^\d{1,5}$/.

Hope that helps. perlretut may help.

Replies are listed 'Best First'.
Re^2: Filtering CGI Input
by awohld (Hermit) on Apr 26, 2005 at 03:45 UTC
    I want to modify this filter so that it will accept lat/longs (-88.88888) that is 9 characters long and can include 0-9 and - and .

    So does this look right?

    ~/^\d|\c(.|-)$/

    All that I really want to do is make sure no other characters get in there except digits (0 thru 9) and the "." and "-" characters.

      9 characters long? Does 1.3456789 count? Or do you really mean 5 digits after the decimal place only? I'm assuming the latter. And that the - sign doesn't count.

      /^-?(\d{1,3}(?:\.\d{1,5})?)$/
      That is, an optional leading - sign, followed by 1 to 3 digits (to allow for 180 degrees East/West), followed, optionally, by a dot, and then 1 to 5 more digits.

      Better yet, try:

      use Regexp::Common; /^$RE{num}{decimal}{-places=>'0,5'}$/ and $_ <= 180;
      No sense reinventing the wheel. :-)