make characters optional in regular expression

前端 未结 3 1583
执笔经年
执笔经年 2020-12-18 19:04

I am trying to validate a (US) phone number with no extra characters in it. so the format is 1-555-555-5555 with no dashes, spaces, etc and the 1 is optional. However, my

相关标签:
3条回答
  • 2020-12-18 19:24

    You haven't done anything to make the 1 optional. You've put it in a group, but that's all. You want this:

    "^1?\\d{10}$"
    

    That basically says to match (in this order):

    • The start of the string
    • Optionally the character '1'
    • Exactly ten digits
    • The end of the string

    Look at the documentation for Pattern for more details. For example, ? is listed in the "Greedy Quantifiers" section like this:

    X?       X, once or not at all

    0 讨论(0)
  • 2020-12-18 19:36

    Use:

    "^1?\\d{10}$"
    

    The ? means "optional".

    0 讨论(0)
  • 2020-12-18 19:38

    Use this one "/^((\+?1-[2-9]\d{2}-[2-9]\d{2}-\d{4})|(\([2-9]\d{2}\)(\s)?[2-9]\d{2}-\d{4}))$/" It will allow only US-allowed numbers which include "1-xxx-xxx-xxxx","+1-xxx-xxx-xxxx",(xxx) xxx-xxxx. I hope this is what you looking for.

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