In the following code I am trying to get the output to be the different formatting of phone numbers and if it is either valid or not. I figured everything out but the Java Regular Expression code on line 11 the string pattern.
import java.util.regex.*;
public class MatchPhoneNumbers {
public static void main(String[] args) {
String[] testStrings = {
/* Following are valid phone number examples */
"(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
/* Following are invalid phone numbers */
"(1234567890)","123)4567890", "12345678901", "(1)234567890",
"(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};
// TODO: Modify the following line. Use your regular expression here
String pattern = "^/d(?:-/d{3}){3}/d$";
// current pattern recognizes any string of digits
// Apply regular expression to each test string
for(String inputString : testStrings) {
System.out.print(inputString + ": ");
if (inputString.matches(pattern)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
}
Basically, you need to take 3 or 4 different patterns and combine them with "|":
String pattern = "\\d{10}|(?:\\d{3}-){2}\\d{4}|\\(\\d{3}\\)\\d{3}-?\\d{4}";
\d{10}
matches 1234567890(?:\d{3}-){2}\d{4}
matches 123-456-7890\(\d{3}\)\d{3}-?\d{4}
matches (123)456-7890 or (123)4567890String str= "^\\s?((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?\\s?";
if (Pattern.compile(str).matcher(" +33 - 123 456 789 ").matches()) {
System.out.println("yes");
} else {
System.out.println("no");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With