Regular expression to match phone number?

前端 未结 5 358
庸人自扰
庸人自扰 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: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])
    

提交回复
热议问题