Looking for a cleaner RegEx solution to matching different formats for a SSN

后端 未结 2 743
鱼传尺愫
鱼传尺愫 2021-01-25 21:10

To see what I want, check out the regex I\'m using. I\'ll try to explain it in English. I want to match 4444 or 444444444 or 444-44-4444.

相关标签:
2条回答
  • 2021-01-25 21:36

    The pattern marked as answer actual fails because it doesn't match the US Spec for valid SSN numbers!

    Using the match invalidator this pattern works and throws out 000 and 666 or numbers which start with 9xx as per the government specification Social Security Number Randomization

    # To use this regex pattern specify IgnoreWhiteSpace due to these comments.
    ^                           # Beginning of line anchor      
    (?!9)                       # Can't be 900- 999                                   
    (?!000)                     # If it starts with 000 its bad (STOP MATCH!)
    (?!666)                     # If it starts with 666 its bad (STOP MATCH!)
    (?<FIRST>\d{3})             # Match the First three digits and place into First named capture group
    (?:[\s\-]?)                 # Match but don't capture a possible space or dash
    (?<SECOND>\d\d)             # Match next two digits
    (?:[\s-]?)                  # Match but don't capture a possible space or dash
    (?<THIRD>\d{4})             # Match the final for digits
    $                           # EOL anchor
    

    I describe the use of the match invalidator on my blog article Regular Expression (Regex) Match Invalidator (?!) in .Net.

    0 讨论(0)
  • 2021-01-25 21:46

    You should be able to do this with backreferences:

    ^(?:\d{3}(-?)\d{2}\1)?\d{4}$
    

    If a - is present, it is captured and can be referenced with \1. If it's not present, \1 will just be empty. So it essentially means: If - is at that position, it must be at the other position too.

    DEMO

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