Reputation: 1682
I have been trying to make a regular expression for my mobile phones but I can't seem to get it to work:
Here are the conditions for my regular expression:
09
9
Here is my regular expression:
[0]{1}[9]{1}[0-9]{7}
Valid mobile number 091123456
Invalid mobile number 0991234567
|| 09912345
Upvotes: 2
Views: 4697
Reputation: 5095
If you use matcher.contains()
instead of matcher.find()
it will match against the whole string instead of trying to find a matching substring. Or you can add ^
and $
anchors as suggested in other answer.
If you don't really need to use a regexp, perhaps it would be more readable to just use
string.startsWith("09") && string.length() == 9
Upvotes: 1
Reputation: 7928
Easiest way:
^09[0-9]{7}$
Explanation:
^09 => begins by 09
[0-9] => any character between 0 and 9
{7} exactly seven times
$ => Ends with the latest group ([0-9]{7})
Upvotes: 4