validate phone number android - java

Im trying to figure out how this validate phone number to my android works.
I have add the code and whant to validate 46123456789 but the last number (9) doesent add to the phone number.
This i use:
/**
* #param phone
* #return The number which satisfies the above criteria, is a valid mobile Number.
* The first digit should contain number between 0 to 9.
* The rest 9 digit can contain any number between 0 to 9.
* The mobile number can have 11 digits also by including 0 at the starting.
* The mobile number can be of 12 digits also by including 46 at the starting
*/
public static boolean isValidPhoneNumber(String phone) {
phone = trimPhoneNumber(phone);
// The given argument to compile() method
// is regular expression. With the help of
// regular expression we can validate mobile
// number.
// 1) Begins with 0 or 46
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
Pattern p = Pattern.compile("(0/46)?[0-9][0-10]{9}");
// Pattern class contains matcher() method
// to find matching between given number
// and regular expression
Matcher m = p.matcher(phone);
return (m.find() && m.group().equals(phone));
}
public static String trimPhoneNumber(String phone) {
if (TextUtils.isEmpty(phone)) {
return phone;
} else {
try {
phone = phone.replace("+46", "");
phone = phone.replaceAll("[^0-9]", "");//replace all except 0-9
return phone;
} catch (Exception e) {
e.printStackTrace();
return phone;
}
}
}
Am i missing something

Use this pattern:
^\s*(?:(?:\+?46)|0)(?:\d){9,10}\s*$
^ at start and $ at end ensure pattern matches the whole input
\s* trim any space or tab
\d capture any digit
(?:\d){9,10} means the pattern (?:\d) should be repeated 9 to 10 times.
``
Pattern start with (+46 or 46) or 0 follow by 9 or 10 digit.
If it could contain - or space between numbers, use this:
^\s*(?:(?:\+?46)|0)(?:[- ]*\d){9,10}\s*$
You could test regex here

Related

Validate a state via its pincode in Java [duplicate]

This question already has answers here:
Why doesn't [01-12] range work as expected?
(7 answers)
Closed 2 years ago.
I need to generate regex to validate state as Tamilnadu based on Pincode validation
Regex which I tried fails at some point
String regex = "^[60-64]{2}{0-9}{4}$";
Ref the Tamil Nadu Pincode info link. It starts with 60-64 as the first two digits, the next 4 digits as 0-9 numbers. It must have six digits.
the code
public boolean isHomeState(String state, String zipcode) {
if (isValidZipCode(zipcode)) {
// ...
}
return true;
}
private boolean isValidZipCode(String zipcode) {
String regex = "^[60-64]{2}{0-9}{4}$";
Pattern p = Pattern.compile(regex);
// If the pin code is empty
// return false
if (zipcode == null) {
return false;
}
Matcher m = p.matcher(zipcode);
return m.matches();
}
Try the following.
Pattern pattern = Pattern.compile("6[0-4]\\d{4}");
In other words, the digit 6 followed by a digit that is either 0 or 1 or 2 or 3 or 4 and ending with exactly four digits.
There are many regex patterns to do it e.g.
6[0-4][0-9]{4} which means 6 followed by a digit in the range, 0 to 4 which in turn followed by exactly 4 digits.
6[0-4]\d{4} which means 6 followed by a digit in the range, 0 to 4 which in turn followed by exactly 4 digits
6[0-4][0-9][0-9][0-9][0-9] which means 6 followed by a digit in the range, 0 to 4 which in turn followed by exactly 4 digits
However, let's analyze your regex, [60-64]{2}[0-9]{4} which will help you understand the problem better.
The regex, [60-64] means only one of the following:
6
A digit in the range 0 to 6
4
And [60-64]{2} means the above repeated exactly two times i.e. it will match with a combination of 2 digits in the range, 0 to 6 e.g. 00, 60, 34, 01, 10, 11 etc.
As a result, the regex, [60-64]{2}[0-9]{4} will match with first 2 digits consisting of digits in the range, 0 to 6 and next 4 digits consisting of digits in the range, 0 to 9 e.g.
012345
123856
234569
101010
202020
303030
404040
505050
606060
111111
222222
333333
which is not something you expect.

Java exception pattern

I'm trying to write a code for exception.
If the input does not match with the pattern below (this is just example) it will throw an exception message.
8454T3477-90
This is the code that I came up with. However, I'm not sure if this is the right patter...
public void setLegalDescription(String legalDescription) throws MyInvalidLegalDescriptionException
{
String valid = ("[0-9999][A-Z][0-9999]-[0-99]");
if (!legalDescription.matches(valid))
{
//throw new MyInvalidLegalDescriptionException("Invalid format! Should be " + "e.g 4050F8335-14");
}
this.legalDescription = legalDescription;
}
Your pattern is slightly off. Try this version:
String valid = ("[0-9]{4}[A-Z][0-9]{4}-[0-9]{2}");
if (!legalDescription.matches(valid))
{
// throw new MyInvalidLegalDescriptionException("Invalid format! Should be " + "e.g 4050F8335-14");
}
An explanation of the regex:
[0-9]{4} any 4 digits
[A-Z] any capital letter
[0-9]{4} any 4 digits
- a dash
[0-9]{2} any 2 digits
It should be noted that [0-9999] does not match any number between 0 and 9999. Rather, it actually just matches a single digit between 0 and 9.
If the width of your identifier is not fixed, then perhaps use this pattern:
[0-9]{1,4}[A-Z][0-9]{1,4}-[0-9]{1,2}

Java Regex mimicking if-else for numbers

Using this as a guide to attempt to emulate an if-else Java regex, I came up with:
[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9])) to do the following:
An optional digit between 0-2 inclusive as the leftmost digit; However, if the first digit is a 2, then the next digit to the right can be maximum 5. If it is a 0 or 1, or left blank, then 0-9 is valid. I am trying to ultimately end up allowing a user to only write the numbers 0-255.
Testing the regular expression on both Regex101 as well as javac doesn't work on test cases, despite the Regex101 explanation being congruent with what I want.
When I test the regex:
System.out.println("0".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ---> false
System.out.println("2".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> true
System.out.println("25".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> false
System.out.println("22".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> false
System.out.println("1".matches("[0-2]?(?:(?<=2)(?![6-9])|(?<!2)(?=[0-9]))")); ----> false
It appears so far, from few test cases, 2 is the only valid case that is accepted by the regex.
For reference, here is my initial regex, using if-else that limits a number to the range of 0-255: [0-2]?(?(?<=2)[0-5]|[0-9])(?(?<=25)[0-5]|[0-9])
I don't see why to mimic if else for checking a range. It's just putting some patterns together.
^(?:[1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$
^ start anchor
(?: opens a non capture group for alternation
[1-9]?\d matches 0-99
1\d\d matches 100-199
2[0-4]\d matches 200-249
25[0-5] matches 250-255
$ end anchor
See demo at regex101
With allowing leading zeros, you can reduce it to ^(?:[01]?\d\d?|2[0-4]\d|25[0-5])$
As you are trying to only allow a range of numbers (0-255), why use regex at all? Instead, parse the string as an int and check if it falls within the range.
public static boolean isInRange(String input, int min, int max) {
try {
int val = Integer.parseInt(input);
return val >= min && val < max;
} catch (NumberFormatException e) {
return false;
}
}

Java check Phone number and matches

i want to check below phone number with matches, phone number conditions :
start with 0 or 9
content must be between 0 and 9
phone number must be 10 character
I tried:
String mobile_number = "9371236569";
if(!TextUtils.isEmpty(mobile_number) &&
mobile_number.matches("^[0][9][0-9]{10}$")) {
}
For number 9371236569 dont work my code and return false,
[ ] Matches any single character in brackets except range with -.
mobile_number.matches("^[09][0-9]{9}$")
^[09] start with eighter 0 or 9.
[0-9]{9} rest 9 digits raging from 0-9.
Use this regex:
"^(0|9)[0-9]{9}$"
Explanation:
^ match beginning of the string
(0|9) match one digit either a 0 or a 9
[0-9]{9} match 9 digits in the range of 0-9
$ match end of the string
public static boolean validateMobile(String moblieNumber) {
boolean check;
Pattern p;
Matcher m;
String MobilePattern = "[0-9]{10}";
p = Pattern.compile(MobilePattern);
m = p.matcher(moblieNumber);
check = m.matches();
return check;
}

Allow any digit in a string other than 9 and 16 digits

^(?![\\s\\S]*(\\d{16})|[\\s\\S]*(\\d{9}))[\\s\\S]*
The above regex does not allow a number greater than 10 digits in the string.
Example, if user enters test 1234567891. The text is a valid text. We should allow user to enter this text.
The user should only not enter a 9 digit number or a 16 digit number.
Example, test 123456789 should be invalid. How to modify the regex.
Is this requirement best served by a regexp ? I think it would be much more readable to check the string length, and if you have a number.
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
and see here.
Don't use a regex for this kind of check. Java has .length() on strings:
private static final Pattern DIGITS = "\\d+";
public boolean inputOK(String input)
{
Matcher m = DIGITS.matcher(input);
int len;
while (m.find()) {
len = m.group().length();
if (len == 9 || len == 16)
return false;
}
return true;
}

Categories