SSN Regex for 123-45-6789 OR XXX-XX-XXXX

前端 未结 6 1276
长发绾君心
长发绾君心 2020-12-04 17:43

Can someone provide me a regex for SSN that matches either

123-45-6789

OR

XXX-XX-XXXX

I currently have ^\\d{3}-?\\d{2}-?\\d{4}$

6条回答
  •  醉话见心
    2020-12-04 18:26

    So you currently have: ^\d{3}-?\d{2}-?\d{4}$

    What you need is to allow any of those numeric blocks to be "X"s instead. This is also fairly simple as a regex - just adapt your existing one to have X instead of \d in each of the three places it occurs: X{3}-?X{2}-?X{4}

    You won't want to be combining a numeric code with and X code, so you just need to allow either one case or the other, so wrap them up in brackets and us a pipe character to specify one or the other, like so:

    ^((\d{3}-?\d{2}-?\d{4})|(X{3}-?X{2}-?X{4}))$
    

    You'll probably also want to allow upper- or lower-case X. This can be specified using [Xx] or by making the whole thing case insensitive, using the i modifier outside the regex.

提交回复
热议问题