Regex For "all The Digits Should Not Be Same For A Mobile Number"
Solution 1:
You can use this regex to check if all the numbers are the same.
(\d)
is a capturing group, \1
matches against the capturing group {9}
matches \1
9 times, you can edit that figure to suit. So This will tell you if ten numbers are the same.
(\d)\1{9}
JS
text.match(/(\d)\1{9}/g);
Solution 2:
In your case, the mobile number is of format (9999) 999-9999 Hence , the regex should be
/\((\d)\1{3}\) \1{3}-\1{4}/.test("(9999) 999-9999")
"true"
/\((\d)\1{3}\) \1{3}-\1{4}/.test("(9999) 929-9999")
"false"
here, the split-up explanation of the regex is
\(
-> matches the ( in your string
(\d)
-> matches the first integer and capture it (so that we could backreference it later)
\1
-> picks the first captured element
{3}
-> checks if the capture is repeating 3 times
(space)
-> space
\1{3}
-> checks if the capture is repeating 3 times(backreferencing)
-
-> checks for hiphen
\1{4}
-> checks if the capture is repeating 4 times
Solution 3:
publicclassregex {
publicstaticvoidmain(String[] args)
{
String regex1 = "(\\d)\\1{9}";
String regex2 = "[\\d]{10}";
Scanner ssc = newScanner(System.in);
System.out.println("enter string:");
String input = ssc.next();
System.out.println(input.matches(regex2)&&(!input.matches(regex1)));
}
}
Solution 4:
If you use any formatting like a separators (-
) you can use as follows
^([2-9])(\d{2})-(\d{3})-(\d{4})(?<!(\1{3}-\1{3}-\1{4}))$
This will allow first digit as only in range of [2-9]
and phone number in format
234-234-2345
This also checks whether same number is used through out number.
Code break up:
**1st Capturing Group ([2-9])**
Match a single character present in the list below [2-9]2-9a single character in the range between 2 (index 50) and 9 (index 57) (case sensitive)
**2nd Capturing Group (\d{2})**
\d{2} matches a digit (equal to [0-9])
{2} Quantifier — Matches exactly 2 times
**-**
matches the character - literally (case sensitive)
**3rd Capturing Group (\d{3})**
\d{3} matches a digit (equal to [0-9])
{3} Quantifier — Matches exactly 3 times
**-**
matches the character - literally (case sensitive)
**4th Capturing Group (\d{4})**
\d{4} matches a digit (equal to [0-9])
{4} Quantifier — Matches exactly 4 times
**Negative Lookbehind (?<!(\1{3}-\1{3}-\1{4}))**
Assert that the Regex below does not match
**5th Capturing Group (\1{3}-\1{3}-\1{4})**
This group matches with character in first group at positions where
our format number will have digits.. i.e., it matches if same
number is repeated in all positions
**$**
asserts position at the end of the string
Solution 5:
publicstaticBooleanisValidMobileNumber(String mobileNo) {
String pattern1 = mobileNo.charAt(0) + "{10}";
String pattern2 = "[\\d]{10}";
return (mobileNo.matches(pattern1) ||!mobileNo.matches(pattern2)) ? false : true;
}
Post a Comment for "Regex For "all The Digits Should Not Be Same For A Mobile Number""