In this example we are going to be validating any phone number. We are going to put following checks against any phone number under test.
Output
Phone Number is Valid
- The phone number should be 10 digit number.
- Splitted by hi-fen(-) and the end result should look like xxx-xxx-xxxx
package com.amzi.xml; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidatePhoneNumber { public static void main(String[] args) { String phNumber = "123-222-3333"; //String phNumber = "123 123 1234"; Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}"); Matcher matcher = pattern.matcher(phNumber); if (matcher.matches()) { System.out.println("Phone Number is Valid"); } else { System.out .println("Phone Number isn't in this formate XXX-XXX-XXXX"); } } }
Output
Phone Number is Valid
Great post.
ReplyDeletePhone Number Locator
Thank you for such a well written article. It’s full of insightful information and entertaining descriptions. Your point of view is the best among many. Ben Luker Australia
ReplyDelete