SPUG: Odd characters in string

John W. Krahn krahnj at telus.net
Thu Jan 25 15:32:08 PST 2007


Eric.D.Peterson at alltel.com wrote:
> How can I count the number of odd (non-alphanumeric, on control)
> characters in a string?   
> 
> For example:  a string "aAA$%\/1
> 50" has  3 numeric, 3 alphabetic, 1 (or 2) control/whitespace (\n or two
> \r\n) and 4 odd characters. I thought maybe a RegEx but I keep getting
> lost with the character escaping.

Perhaps you meant the string:

"aAA\$%\1
50"

instead.  The variable $% interpolates in a double quoted string and "\/"
interpolates as "/".

$ perl -le'
my $str = "aAA\$%\1
50";
print for $str =~ s/([[:digit:]])/$1/g,
          $str =~ s/([[:alpha:]])/$1/g,
          $str =~ s/([[:cntrl:]])/$1/g,
          $str =~ s/([[:punct:]])/$1/g;
'
2
3
2
2

The substitution operator returns the number of characters that were
substituted and the POSIX character classes (should) work with any non-ASCII
character sets.




John
-- 
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order.       -- Larry Wall


More information about the spug-list mailing list