Home > Back-end >  validate "sub groups" inside a number using regex
validate "sub groups" inside a number using regex

Time:10-04

I'm trying to validate a SSN input, the rules I need to validate are:

  • the 1st group, can only be digits and can't be "000"
  • the 2nd group, can only be digits and can't be "00"
  • the 3rd group, can only be digits and can't be "0000"
  • the whole expression can't be either "000000000" or "111111111" or "333333333" or "123456789"

I came up with this regex validation, but it doesn't look like it's working correctly with these rules, I need help to understand what I'm doing wrong, any help would be appreciated

^(?!000)\d{3}(?!00)\d{2}(?!0000)\d{4}(?!000000000|111111111|333333333|123456789)\d{9}$

CodePudding user response:

You may try this regex for your validation checks:

^(?!(?:([013])\1{8}|123456789)$|000|\d{3}00|\d{5}0000)\d{9}$

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (?!: Start lookahead
    • (?:: Start non-capture group
      • ([013]): Match digit 0 or 1 or 3 in capture group #1
      • \1{8}: Match 8 repetitions of same digit captured in group #1
      • |: OR
      • 123456789: Match 123456789
    • ): End non-capture group
    • $: End
    • |: OR
    • 000: Match 000
    • |: OR
    • \d{3}00: Match any 3 digits followed by 00
    • |: OR
    • \d{5}0000: Match any 5 digits followed by 0000
  • ): End negative lookahead
  • \d{9}: Match 9 digits
  • $: End

CodePudding user response:

You can put the negative lookahead at the beginning and that will also now allow all zeroes, so you don't have to add the separate checks like (?!000) as the total number of digits is 9.

If you want separate groups, you can capture them.

^(?!(?:000000000|111111111|333333333|123456789)$)(\d{3})(\d{2})(\d{4})$

Regex demo

Or in short with a capture group for either 1, 3 or 0 and a backreference:

^(?!(?:([013])\1{8}|123456789)$)(\d{3})(\d{2})(\d{4})$

Regex demo

  • Related