OK I am learning how to use regex in perl and here is my code:
my $name = 'Tom Anderson';
if( $name =~ /(\w) (\w)/ )
{
print "Good\n";
print "$1 + $2";
}
outputs: good m + A
My understanding is that the regular expression will check $name
as follows:
a word character followed by a space followed by another word character, this does not work 100%. if somebody enters another name, say a middle name the if statement still works. I only want two names and nothing else. Why is it succeeding when someone enters a third?
And the capturing using the parentheses when I print the $1 and $2 gives me m
and A
. Why is that? Why isn't the capturing giving me Tom
and Anderson
?
Modify your regex:
$name =~ /(\w+) (\w+)/;
You can also anchor this regex to the start and end of the line:
$name =~ /^(\w+) (\w+)$/;
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.