HDuck
HDuck

Reputation: 395

How can I check if a user-entered string matches a specific format?

I'm writing a program to check if a string the user enters is a valid phone number. The only qualification for a valid number is matches the format "ddd-ddd-dddd" where each d is a digit. How do I check if the string matches this format?

Upvotes: 0

Views: 4984

Answers (5)

Jonathan
Jonathan

Reputation: 11

I'm not great with java but if i remember right,

To validate a string in java looks like this:

if(cellnum.matches(\\d{3}-\\d{3}-\\d{4})
{//this is valid}

Upvotes: 0

Umesh Patil
Umesh Patil

Reputation: 10685

You should use regular expression. Below is few lines of code that will be useful.

  String sPhoneNumber1 = "605-888-9999";
  String sPhoneNumber2 = "605-888-9991";
  //String sPhoneNumber3 = "605-8838-9993";

  Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{3}");
  Matcher matcher = pattern.matcher(sPhoneNumber);

  if (matcher.matches()) {
      System.out.println("Phone Number Valid");
  }
  else
  {
      System.out.println("Phone Number must be in the form XXX-XXXXXXX");
  }

Upvotes: 2

Justin Mitchell
Justin Mitchell

Reputation: 304

You would use a regular expression to match it. The easiest regular expression to match it is:

/[0-9]{3}-[0-9]{3}-[0-9]{4}/

You can also use:

/\d{3}-\d{3}-\d{4}/

Javascript:

var test = '111-222-3333';
var regex = /\d{3}-\d{3}-\d{4}/g;
console.log(test.match(regex));

Expected output:

["111-222-3333"]

Wiki has a good source for learning regular expressions: http://en.wikipedia.org/wiki/Regular_expression

There are also heaps of online resources.

Edit: Missed the Java requirement From the Java 7 docs: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

Applying that to above:

Pattern p = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Matcher m = p.matcher("111-222-3333");
boolean b = m.matches();

if (b) {
System.out.println("Matches!");
} else {
System.out.println("Doesn't match!");
}

Remember to escape () your backslashes when using string literals in Java.

Upvotes: 0

Leo Pflug
Leo Pflug

Reputation: 544

String s = "123-345-6789";
if(!s.matches("^\\d{3}-\\d{3}-\\d{4}$"))
{
    System.out.println("This is not a valid phone number");
}
else
{
    System.out.println("This is a valid phone number");
}

And here a good site to learn regex: http://regexone.com/

Upvotes: 0

Moh-Aw
Moh-Aw

Reputation: 3018

String whatUserEntered = "1223-123-1234";
System.out.println(Pattern.matches("\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d", whatUserEntered));

Upvotes: 0

Related Questions