fixxxer
fixxxer

Reputation: 16154

How can I check if a Perl string contains letters?

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

Would this be fine?

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

Upvotes: 7

Views: 54941

Answers (6)

Eugen Konkov
Eugen Konkov

Reputation: 25217

[^\W0-9_]

# or

[[:alpha:]]

See perldoc perlre

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342739

try this:

/[a-zA-Z]/

or

/[[:alpha:]]/

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

also read perldoc perlrequick

Edit: @OP, you have provided example string, but i am not really sure what you want to do with it. so i am assuming you want to check whether a word is all letters, all numbers or something else. here's something to start with. All 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";

output

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

Upvotes: 15

Anonymous
Anonymous

Reputation: 50379

If you're looking to detect whether something looks like a number for the purposes of manipulating it in Perl, you'll want Scalar::Util::looks_like_number (core since perl 5.7.3). From perlapi:

looks_like_number

Test if the content of an SV looks like a number (or is a number). Inf and Infinity are treated as numbers (so will not issue a non-numeric warning), even if your atof() doesn't grok them.

Upvotes: 0

Greg Bacon
Greg Bacon

Reputation: 139631

Using /[A-Za-z]/ is a US-centric way to do it. To accept any letter, use one of

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

The third one employs a double-negative: not not-a-letter, not a digit, and not an underscore.

Whichever you choose, those who maintain your code will certainly appreciate it if you stick with one consistently!

Upvotes: 0

Rubens Farias
Rubens Farias

Reputation: 57976

If you're looking for any kind of letter from any language, you should go with

\p{L}

Take a look on this full reference: Unicode Character Properties

Upvotes: 5

Makis
Makis

Reputation: 12988

If you want to match Unicode characters rather than just ASCII ones, try this:

#!/usr/bin/perl

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

Upvotes: 9

Related Questions