This post is a part of the daily blog series
A Tip A Day, daily dosage of learning!
Day #7 – US Phone Validation Using RegEx (Regular Expression)
US Phone Number : 222-333-4444
String phone = '222-333-4444'; String WrongPhone = '222-333' //This is the pattern that matches with the above phone number format String regExPhone = '^[0-9]\\d{2}-\\d{3}-\\d{4}$'; //The below result would give TRUE, because the pattern matches with String Phone Boolean valid = Pattern.matches(regExPhone,phone); //Checking the pattern match for WrongPhone. This would result in FALSE Boolean valid2 = Pattern.matches(regExPhone,WrongPhone);
US Phone Number With Extension: 222-333-4444×1234
String phone = '222-333-4444'; String phoneWithExtn = '222-333-4444x1234' //This is the pattern that matches with the above phone number format String regExPhoneWithExtn = '^[0-9]\\d{2}-\\d{3}-\\d{4}x\\d*$'; //The below result would give TRUE, because the pattern matches with String PhoneWithExtn Boolean valid = Pattern.matches(regExPhoneWithExtn,phoneWithExtn); //Checking the pattern match for just phone. This would result in FALSE Boolean valid = Pattern.matches(regExPhoneWithExtn,phone);
Useful Links
The 2 links below help to test your regular expressions and also explain how to build regular expressions for different string formats. You can learn to build the regular expressions. Give a try.
http://regexlib.com/RETester.aspx?regexp_id=22
Read all other tips of the blog series here – A Tip A Day, daily dosage of learning!
One Reply to “A Tip A Day #7 – US Phone Validation Using RegEx”