Given string str, the task is to check whether the given string is valid SSN (Social Security Number) or not by using Regular Expression Validate Your SSN Now.
The valid SSN (Social Security Number) must satisfy the following conditions:
Examples:
Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer.
Get the String.
Create a regular expression to Check valid SSN (Social Security Number) as mentioned below:
regex = "^(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$";
Below is the implementation of the above approach:
C++
// C++ program to validate the
// SSN (Social Security Number)
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
// Function to validate the SSN
// (Social Security Number)
bool isValidSSN(string str)
{
}
// Driver Code
int main()
{
// Test Case 1:
string str1 = "856-45-6789";
cout << isValidSSN(str1) << endl;
}
** SSN Validator Java Program
**
// Java program to check valid
// SSN (Social Security Number) using
// regex.
import java.util.regex.*;
class GFG {
}
Python3
import re
def isValidSSN(str):
str1 = "856-45-6789"
print(isValidSSN(str1))
str2 = "000-45-6789"
print(isValidSSN(str2))
str3 = "856-452-6789"
print(isValidSSN(str3))
str4 = "856-45-0000"
print(isValidSSN(str4))
C#
// C# program to validate the
// SSN (Social Security Number)
//using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG
{
Console.WriteLine( isValidSSN(s) ? "true" : "false");
}
Console.ReadKey(); }
}
// Javascript program to validate
// SSN (Social Security Number) using Regular Expression
// Function to validate the
// SSN Code
function isValidSSN(str)
// Regex to check valid
// SSN CODE
let regex = new RegExp(/^(?!666)\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/);
}
// Driver Code
// Test Case 1:
let str1 = "856-45-6789";
console.log(isValidSSN(str1));
// Test Case 2:
let str2 = "000-45-6789";
console.log(isValidSSN(str2));
// Test Case 3:
let str3 = "856-452-6789";
console.log(isValidSSN(str3));
// Test Case 4:
let str4 = "856-45-0000";
console.log(isValidSSN(str4));
// This code is contributed by Rahul Chauhan
Output
true
false
false
false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!