Regular expression to match phone number?

前端 未结 5 364
庸人自扰
庸人自扰 2021-01-21 12:36

I want to match a phone number that can have letters and an optional hyphen:

  • This is valid: 333-WELL
  • This is also valid: 4URGENT
5条回答
  •  猫巷女王i
    2021-01-21 12:47

    Not sure if this counts, but I'd break it into two regexes:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $text = '333-URGE';
    
    print "Format OK\n" if $text =~ m/^[\dA-Z]{1,6}-?[\dA-Z]{1,6}$/;
    print "Length OK\n" if $text =~ m/^(?:[\dA-Z]{7}|[\dA-Z-]{8})$/;
    

    This should avoid accepting multiple dashes, dashes in the wrong place, etc...

提交回复
热议问题