Sunday, January 27, 2019

Java Program 2: Verify the given mobile number contains 10 digits and starts with 7, 8 or 9 only

There will be many approaches to solve this problem, we will use regular expressions to solve this in this post.

First we will regular expression that satisfies given conditions, then we will match with the given inputs.

Condition 1: Mobile number must start with 7, 8 or 9, so we will write ^[789] or ^[7-9]
  • ^ indicates starting of the number
  • [789] or [7-9] indicates 7 or 8 or 9
So first digit condition is satisfied.

Condition 2: It must contain 10 digits, so we will write [0-9]{9}
  • [0-9] indicates any number between 0 to 9 including 0,9
  • {9} indicates it allows [0-9] 9 times. [0-9]{9} means any number between 0 and 9 (including 0,9) can repeat 9 times after first digit
So second condition also satisfied. ^[789][0-9]{9} will be the final regular expression. Checkout the below program, give multiple inputs and verify the output.

Checkout the sample outputs below

Please let me know if this program fails for any of your inputs, I will verify and update.

#HappyLearning #HappyTesting

1 comment:

Java Program 5: How to reverse given string and each word of it?

Let us understand the problem with an example, suppose "Learn Core Java" is the given string then the expected output should be &...