Robert
Robert

Reputation: 10390

perl regular expression for inserting a character without using functions at certain points

I am trying to write a script that checks to see that a string has 9 characters. This string will be divided into 3 sets/groups. First group having three numbers, second group having two numbers and third having four numbers. I want to capture these using parentheses and print them out. I wrote the following thinking it was 100% correct but it is not working:

my $numbers =  123456789;

( my $three, my $two, my $four ) = ( $numbers =~ /([0-9]{3})([0-9]{2})([0-9]{4})/);
print "$three-$two-$four";

It prints 123-4567

From my understanding the above regex says, "a digit between 0-9 with 3 repetitions and capture the value, a digit between 0-9 with 2 repetitions and capture the value, a digit between 0-9 with 4 repetitions and capture the value, and nothing else. There cannot be any other chars before or after the numbers."

Upvotes: 1

Views: 44

Answers (1)

ikegami
ikegami

Reputation: 386501

You need to make sure the digits start at the start of the string and end at the end of the string, otherwise 1234567891 will match.

my ($first, $second, $third) = $number =~ /^([0-9]{3})([0-9]{2})([0-9]{4})\z/
   or die("Invalid input\n");

print "$first-$second-$third\n";

Upvotes: 2

Related Questions