问题
I want to validate phone number with following conditions:
- length should be 10 digits
- should start with 7 or 8 or 9
If it does not meet these requirements, we should fail the number.
I have tried the following:
print "Enter phone number: \n";
$name=<>;
chomp $name;
if (length($name)==10 && $name==~ m{/[^7-9]/}){
print "$name is valid \n";
}
else {
print "$name is not valid \n";
}
回答1:
I would just use a single regex here:
^[789][0-9]{9}$
This avoids having to spread your validation logic across a few places.
if ($name =~ m{/^[789][0-9]{9}$/}){
print "$name is valid \n";
}
else {
print "$name is not valid \n";
}
回答2:
It might be worth explaining what was wrong with your original version. You have two checks. The first one (length($name)==10
) is fine. The problems are with the second one.
$name==~ m{/[^7-9]/}
There are three problems here. Firstly, you're using the wrong operator. You know you need to bind your variable ($name
) to your match operator, but the binding operator is =~
not ==~
. But, unfortunately, your operator isn't wrong enough to throw a syntax error. Perl will interpret it as a numeric comparison (==
) followed by a bitwise negation (~
). That's certainly not what you want!
Your second problem is with the match operator. It looks like you know that the match operator is m/.../
and that you also know you can choose an alternative delimiter for the match operator - you've picked m{...}
. But you shouldn't nest those delimiters. When you use m{/.../}
you're are looking for two literal characters /
in your string.
Finally, there's a problem with your actual regex. You want the string to start with 7, 8 or 9. Putting those digits in a character class ([7-9]
) is a good idea. But you shouldn't also place the start of string anchor (^
) inside the character class. At the start of a character class, ^
has a different meaning - it means "not one of the characters listed here". So your character class ends up meaning the exact opposite of what you wanted it to mean.
Your match expression should have looked like this:
$name =~ m{^[7-9]}
Making your complete code:
print "Enter phone number: \n";
$name = <>;
chomp $name;
if (length($name) == 10 and $name =~ m{^[7-9]}) {
print "$name is valid \n";
}
else {
print "$name is not valid \n";
}
(I did a little tidying - adding some whitespace around operators and switching &&
for and
as is has lower precedence. You might also consider revising your variable name. $name
is not a great name for a variable that contains a phone number!)
来源:https://stackoverflow.com/questions/54862088/validating-phone-number-using-perl