user2663377
user2663377

Reputation: 37

how can i match two consecutive words that both start with capital letters?

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

Answers (2)

ikegami
ikegami

Reputation: 385917

/^ \s* \p{Lu}\S+ \s+ \p{Lu}\S+ \s* \z/x

Upvotes: 0

fugu
fugu

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]
  • Char class [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]
  • Char class [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 line

Upvotes: 4

Related Questions