Reputation: 1965
I have a Perl string that is only allowed to contain the letters A to Z (capital and lowercase), the numbers 0 to 9, and the "-" and "_" characters. I want to remove all non-matching characters from the string, leaving the rest untouched.
So "Hell@_World" would become "Hell_World".
Upvotes: 0
Views: 2252
Reputation: 54465
You would use a substitution with the ^
(not) regular expression. While Perl offers shortcuts, you can see the parts more clearly like this:
$string =~ s/[^[:alnum:]_-]//g;
where the [:alnum:]
is the character class for alphabetic and numeric characters. The "-
" is last in the brackets to avoid confusing it as part of a range of characters.
Upvotes: 3