How to check if a Perl string contains letters?

In Perl, what regular expression should I use to find if a string of characters has letters or not? Example used string:Thu Jan 1 05:30:00 1970

Would that be good?

    if ($l =~ /[a-zA-Z]/)
 {
    print "string ";    
 }
 else
 {      
    print "number ";    
 }
+5
source share
5 answers

try the following:

/[a-zA-Z]/

or

/[[:alpha:]]/

Otherwise, you should give examples of the strings you want to match.

also read perldoc perlrequick

Edit: @OP, you provided an example string, but I'm not quite sure what you want to do with it. so I suppose you want to check if all letters, all numbers, or something else. here's where to start. Everything from perldoc perlrequick (and perlretut), so please read them.

sub check{
    my $str = shift;
    if ($str =~ /^[a-zA-Z]+$/){
        return $str." all letters";
    }
    if ($str =~ /^[0-9]+$/){
        return $str." all numbers";
    }else{
        return $str." a mix of numbers/letters/others";
    }
}

$string = "99932";
print check ($string)."\n";
$string = "abcXXX";
print check ($string)."\n";
$string = "9abd99_32";
print check ($string)."\n";

Exit

$ perl perl.pl
99932 all numbers
abcXXX all letters
9abd99_32 a mix of numbers/letters/others
+14
source

Unicode, ASCII, :

#!/usr/bin/perl

while (<>) {
  if (/[\p{L}]+/) {
    print "letters\n";
  } else {
    print "no letters\n";
  }
}
+9

,

\p{L}

: Unicode

+5

/[A-Za-z]/ - . ,

  • /[[:alpha:]]/
  • /\p{L}/
  • /[^\W\d_]/

: not not-a-letter, , .

, , , , , !

0

, - Perl, Scalar:: Util:: looks_like_number ( perl 5.7.3). perlapi:

looks_like_number

Check if the contents of the SV look like a number (or number). Inf and Infinity are treated as numbers (therefore, a non-numeric warning will not be issued), even if your atof () does not grok them.

0
source