Regular expression to match phone number?

前端 未结 5 362
庸人自扰
庸人自扰 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.

提交回复
热议问题