SPUG: Odd characters in string

DeRykus, Charles E charles.e.derykus at boeing.com
Thu Jan 25 15:53:12 PST 2007


 


> 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.

Here's a slight variant:

my $alnum =0;
$alnum++  while $str =~ /[[:alnum:]]/g;
print "non alnum: ",  length($str)-$alnum, "\n";

-- 
Charles DeRykus


More information about the spug-list mailing list