Aadhaar Number Validator Using Java
Java program to validate and extract Aadhaar numbers from text using regex in a file.
- The program starts by defining a file path to the text file that will be read.
- Inside the
mainmethod, aScannerobject is created to read the file. - A
whileloop is used to iterate through each word in the file using theScannerobject. - The regular expression pattern
\\d{4}-\\d{4}-\\d{4}is defined to match Aadhaar numbers in the format of "####-####-####" (four digits, a hyphen, four digits, a hyphen, and four digits). - Each word from the file is checked for the presence of a colon (":") using the
lastIndexOfmethod. If a colon is found, the program assumes that the Aadhaar number is present after the colon. - The Aadhaar number is extracted from the word using
substringstarting from the index after the colon. - A
Patternobject is created using the regular expression pattern. - The
Matcherobject is initialized with the extracted number and the pattern. - The
findmethod of theMatcherobject is called to check if the number matches the defined pattern. - If a match is found, it prints that the number is a valid Aadhaar number. Otherwise, it prints that the number is not a valid Aadhaar number.
- The
catchblock handles theFileNotFoundExceptionin case the specified file is not found.
Note: The code uses @SuppressWarnings("resource") annotation, which suggests that the Scanner object is not closed explicitly because it goes out of scope when the loop ends. However, it's generally recommended to close resources like Scanner explicitly using the close method or by utilizing the try-with-resources statement to ensure proper resource management.
Make sure to provide a valid file path to an existing text file for the program to read and search for Aadhaar numbers.
TextFile Content :
user1:2222-3333-4444
user2:4444-5555-32
Result:
2222-3333-4444 is valid Addhar Number.
4444-5555-32 is not valid Addhar Number.
Project Files
/
Loading...
| .. | ||
| This directory is empty. | ||