Reputation: 37
I want to match first and last name.
e.g. Robert Still, the words can be preceeded and followed by whitespaces however the string can only contain two words.
' Robert Still ' = true
' Robert Still ' = true
'e Robert Still 4 ' = false
this is the code that i tried
m/^\s*[A-Z].*[a-z]\s*[A-Z].*[a-z]\s*$/
Upvotes: 1
Views: 154
Reputation: 6578
Try this:
#!/usr/bin/perl -w
use strict;
my @names = ('Robert Still', ' Robert Still', 'Robert Still ', '4 Robert Still 2', 'Robert e Still');
foreach (@names){
if ($_ =~ /(^\s*[A-Z]\w+\s+[A-Z]\w+\s*$)/){
print "'$_' : true\n"
}
else {
print "'$_' : false\n";
}
}
Output:
'Robert Still' : true
' Robert Still' : true
'Robert Still ' : true
'4 Robert Still 2' : false
'Robert e Still' : false
Regex explained:
^
Start of line \s*
0 to infinite times [greedy] Whitespace [\t \r\n\f\v][A-Z]
matches: A-Z A character range between Literal A and Literal Z\w+
1 to infinite times [greedy] Word character [a-zA-Z_\d]\s+
1 to infinite times [greedy] Whitespace [\t \r\n\f\v][A-Z]
matches: A-Z A character range between Literal A and Literal Z \w+
1 to infinite times [greedy] Word character [a-zA-Z_\d]\s*
0 to infinite times [greedy] Whitespace [\t \r\n\f\v]$
End of lineUpvotes: 4