in reply to Inverse regexes for input validation

/^[^A-Za-z\-\ ]+$/ will only match if the string contains only bad characters.

sub validate_text { my ($text) = @_; if ($text =~ s/[^A-Za-z0-9 -]+//g) { print "Funny business fixed\n"; } else { print "Text was already clean\n"; } return $text; } my $validated = validate_text($test1);

Replies are listed 'Best First'.
Re^2: Inverse regexes for input validation
by chris-lon (Initiate) on Mar 28, 2007 at 17:00 UTC
    thanks for that, seems I overcomplicated it far too much and wasn't using local vars properly

    turns out all I needed was
    my ($text) = @_; $text =~ s/[^A-Za-z0-9 -]+//g; return $text;
    thanks very much for the help.
      Not that it makes a whole lot of difference in your case, but the "tr///" operator is especially good for this sort of thing -- it's demonstrably faster than "s///" (utf8 wide characters don't even seem to slow it down), and the syntax is a little easier:
      my ( $text ) = shift; $text =~ tr/ 0-9A-Za-z-//cd; return $text;
      The "c" modifier says the match should apply to the complement of the characters cited, and with no characters in the replacement side, "d" says delete all matched characters.