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 ";
}
To check if a string contains any letters, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise.
Using the Perl index() function The index() function is used to determine the position of a letter or a substring in a string. For example, in the word "frog" the letter "f" is in position 0, the "r" in position 1, the "o" in 2 and the "g" in 3. The substring "ro" is in position 1.
Word character \w[0-9a-zA-Z_]: The \w belongs to word character class. The \w matches any single alphanumeric character which may be an alphabetic character, or a decimal digit or punctuation character such as underscore(_). It will match only single character word, not the whole word.
The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.
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
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";
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With