Regular expression to match phone number?

前端 未结 5 359
庸人自扰
庸人自扰 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条回答
  • 2021-01-21 12:43

    Supposing that you want to allow the hyphen to be anywhere, lookarounds will be of use to you. Something like this:

    ^([A-Z0-9]{7}|(?=^[^-]+-[^-]+$)[A-Z0-9-]{8})$
    

    There are two main parts to this pattern: [A-Z0-9]{7} to match a hyphen-free string and (?=^[^-]+-[^-]+$)[A-Z0-9-]{8} to match a hyphenated string.

    The (?=^[^-]+-[^-]+$) will match for any string with a SINGLE hyphen in it (and the hyphen isn't the first or last character), then the [A-Z0-9-]{8} part will count the characters and make sure they are all valid.

    0 讨论(0)
  • 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...

    0 讨论(0)
  • 2021-01-21 12:49

    You seek the alternation operator, indicated with pipe character: |

    However, you may need either 7 alternatives (1 for each hyphen location + 1 for no hyphen), or you may require the hyphen between 3rd and 4th character and use 2 alternatives.

    One use of alternation operator defines two alternatives, as in:

    ({3,3}[0-9A-Za-z]-{4,4}[0-9A-Za-z]|{7,7}[0-9A-Za-z])
    
    0 讨论(0)
  • 2021-01-21 12:52

    Thank you Heath Hunnicutt for his alternation operator answer as well as showing me an example.

    Based on his advice, here's my answer:

    [A-Z0-9]{7}|[A-Z0-9][A-Z0-9-]{7}
    

    Note: I tested my regex here. (Just including this for reference)

    0 讨论(0)
  • 2021-01-21 12:57

    I think this should do it:

    /^[a-zA-Z0-9]{3}-?[a-zA-Z0-9]{4}$/
    

    It matches 3 letters or numbers followed by an optional hyphen followed by 4 letters or numbers. This one works in ruby. Depending on the regex engine you're using you may need to alter it slightly.

    0 讨论(0)
提交回复
热议问题