Sadu
Sadu

Reputation: 97

Java Regex match exact SSN pattern

I want to capture exact SSN pattern DDD-DD-DDDD from the input string not the other pattern DDD-DD-DDDD-DDD

String line = " Hello my SSN : 111-22-3333-444 and another SSN: 333-56-3789" ;
    
Pattern p = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");
Matcher m = p.matcher(line);
while(m.find()) {
    System.out.println(m.group() );
}

I'm getting output as

111-22-3333
333-56-3789

Expected Output: 333-56-3789

I tried adding \b boundaries still no luck

Upvotes: 0

Views: 212

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You can use

(?<!\d|\d[.-])\d{3}(?=([.-]))\1\d{2}\1\d{4}(?![.-]?\d)

See the regex demo. Details:

  • (?<!\d|\d[.-]) - no digit nor digit + - / . immediately to the left is allowed
  • \d{3} - three digits
  • (?=([.-])) - a positive lookahead that captures the next char that must be . or -
  • \1 - same value as captured with the capturing group in the lookahead
  • \d{2} - two diigits
  • \1 - same value as captured with the capturing group in the lookahead
  • \d{4} - four digits
  • (?![.-]?\d) - no - / . + digit or just digit is allowed immediately to the right of the current location.

See the Java demo:

String line = "Hello my 1st SSN : 11.333.56.3788 , 2nd SSN: 333-56-3789 , 3rd SSN 333.56.3780" ;
Pattern p = Pattern.compile("(?<!\\d|\\d[.-])\\d{3}(?=([.-]))\\1\\d{2}\\1\\d{4}(?![.-]?\\d)");
Matcher m = p.matcher(line);
while(m.find()) {
    System.out.println(m.group() );
}
// => 333-56-3789 and 333.56.3780

Upvotes: 1

Related Questions