How can I validate mobile numbers with a regular expression?
Iran Mobile phones have numeral system like this:
091- --- ----
093[1-9] --- ----
Some examples for prefixes:
0913894----
0937405----
0935673----
0912112----
Source: http://en.wikipedia.org/wiki/Telephone_numbers_in_Iran
Best Regular Expression for Detect Iranian Mobile Phone Numbers
I'm sure its best regular expression for detect iranian mobile number.
(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}
use in javascript
var
mobileReg = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/ig,
junkReg = /[^\d]/ig,
persinNum = [/۰/gi,/۱/gi,/۲/gi,/۳/gi,/۴/gi,/۵/gi,/۶/gi,/۷/gi,/۸/gi,/۹/gi],
num2en = function (str){
for(var i=0;i<10;i++){
str=str.replace(persinNum[i],i);
}
return str;
},
getMobiles = function(str){
var mobiles = num2en(str+'').match(mobileReg) || [];
mobiles.forEach(function(value,index,arr){
arr[index]=value.replace(junkReg,'');
arr[index][0]==='0' || (arr[index]='0'+arr[index]);
});
return mobiles;
};
// test
console.log(getMobiles("jafang 0 91 2 (123) 45-67 jafang or +۹۸ (۹۱۵) ۸۰ ۸۰ ۸۸۸"));
support all option like these
912 123 4567
912 1234 567
912-123-4567
912 (123) 4567
9 1 2 1 2 3 4 5 6 7
9 -1 (2 12))3 45-6 7
and all with +98 or 0
+989121234567
09121234567
9121234567
or even persian numbers
+۹۸ (۹۱۵) ۸۰ ۸۰ ۸۸۸
and only detect true iranian operator numbers 091x 092x 093x 094x
for more info : https://gist.github.com/AliMD/6439187
Simplicity is the beautify of life . Try this one :
^09[0|1|2|3][0-9]{8}$
//091 for Hamrahe-Aval Operator
//092 for Rightel Operator
//093 | 090 for Irancel Oprator
Here is an Extension method in c# which I use regularly in my project :
public static bool IsValidMobileNumber(this string input)
{
const string pattern = #"^09[0|1|2|3][0-9]{8}$";
Regex reg = new Regex(pattern);
return reg.IsMatch(input);
}
Using like this :
If(!txtMobileNumber.Text.IsValidMobileNumber())
{
throw new Exception("Mobile number is not in valid format !");
}
According to the wiki page http://en.wikipedia.org/wiki/Telephone_numbers_in_Iran#Mobile_phones, the matches are:
091x-xxx-xxxx
0931-xxx-xxxx
0932-xxx-xxxx
0933-xxx-xxxx
0934-xxx-xxxx
0935-xxx-xxxx
0936-xxx-xxxx
0937-xxx-xxxx
0938-xxx-xxxx
0939-xxx-xxxx
which looks like
(the specific sequence 09) (1 followed by 0-9 OR 3 followed by 1-9) (7 digits)
Assuming you dont care about the dashes for now, this translates to
09 (1 [0-9] | 3 [1-9]) [0-9]{7} <-- spaces added for emphasis
09(1[0-9]|3[1-9])[0-9]{7} <-- actual regex
(the (..|..) does OR, the [0-9]{7} says match exactly 7 digits, ...)
If you want dashes in the specified location:
09(1[0-9]|3[1-9])-?[0-9]{3}-?[0-9]{4}
should match
How about this one ?
^(\+98?)?{?(0?9[0-9]{9,9}}?)$
working for:
09036565656
09151331685
09337829090
09136565655
09125151515
+989151671625
+9809152251148
check out the results here
^(\+98|0)?9\d{9}$
Will match with numbers like +989123456789 and
^[0][9][0-9][0-9]{8,8}$
match with numbers like 09123456789
^09\d{2}\s*?\d{3}\s*?\d{4}$
This will also allow spaces between numbers (if they are 4-3-4).
First of all lets write the reg ex for the numbers
^09\d{9}$ which means it must start with 09 and followed by 9 digits
or instead of \d you can use ^09[0-9]{9}$
after that
Regex objNotNaturalPattern=new Regex("[^09[0-9]{9}]");
objNotNaturalPattern.IsMatch(yourPhoneNumber);
Hope this helps.
in javascript you can use this code
let username = 09407422054
let checkMobile = username.match(/^0?9[0-9]{9}$/)
it will return
["9407422054", index: 0, input: "9407422054", groups: undefined]
the best regex pattern
(+?98|098|0|0098)?(9\d{9})
\A09\d{9} should do it for you
To support the 0903---- Irancell mobile numbers, use:
^(0|\+98)?([ ]|,|-|[()]){0,2}9[0|1|2|3|4]([ ]|,|-|[()]){0,3}(?:[0-9]([ ]|,|-|[()]){0,2}){8}$
I used this for Iran Mobile and worked for Irancell , rightell and MCI 0935-0939 ,0912,0901,0910,0902,0903,...
public static MobilePattern: string = '09[0-9]{9}$';
Regex:
/^(\{?(09)([1-3]){2}-([0-9]){7,7}\}?)$/
Matches:
- 0913-1234567
- 0933-1234567
Doesn't match:
- 0944-1234567
- 0955-1234567
If you don't want the '-', simply remove it from the regex
string sPattern = "^09[-.\\s]?\\d{2}[-.\\s]?\\d{3}[-.\\s]?\\d{4}$";
if (System.Text.RegularExpressions.Regex.IsMatch(stringToMatch, sPattern)){
System.Console.WriteLine("Phone Number is valid");
} else {
System.Console.WriteLine("Phone Number is invalid");
}
The expression above will match any number starting with 09 followed by a space, dot, or dash if present, then 2 digits, etc
ex: 09001234567 or 09 11 123 4567 or 09-01-123-4567 or 09.01.123.4567 or 0900.000.0000 or 0900-000-0000 or 0900.000-0000 etc
^09(1\d|3[1-9])-\d{3}-\d{4}$
is the regular expression that you need:
Starting with the beginning of the string (so no other digits sneak in)
09 is constant
1 can be combined with any subsequent digit, 3 cannot be combined with 0
-, and 3 digits
-, and 4 digits
End of string (again, so no other digits sneak in)
... but don't take my word for it, run it (I would recommend adding more test numbers):
List<string> possible = new List<string> { "091-555-8888",
"0915-888-4444",
"0930-885-8844",
"0955-888-8842" };
string regex = #"09(1\d|3[1-9])-\d{3}-\d{4}$";
foreach (string number in possible)
{
Console.WriteLine("{0} is{1} an Iranian number", number, Regex.IsMatch(number, regex) ? "" : " not");
}
It's Simple.
Iran TCI Phone in Any Format
Supports These Formats
+98217777777
98217777777
098217777777
0098217777777
217777777
0217777777
function IsIranPhone(phone) {
if (phone == null || phone ==undifined) {
return false;
}
return new RegExp("^((|0|98|098|0098|\\+98)[1-8][1-9][2-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])$").test(phone);
}
Using this code in C#
public bool IsMobileValid(string mobile)
{
if (string.IsNullOrWhiteSpace(mobile))
return false;
if (Regex.IsMatch(mobile, #"(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()])
{0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}"))
return true;
return false;
}
//check phone number
function check_phone(number) {
var regex = new RegExp('^(\\+98|0)?9\\d{9}$');
var result = regex.test(number);
return result;
}
$('#PhoneInputId').focusout(function () {
var number = $('#crt-phone').val();
if (!check_phone(number)) {
your massage...
} else {
your massage...
}
});
this is best answer, i tested all answers but this is easy and best
Related
EDIT 2:
Yes like I thought, i need to change the pattern to 2 different ones, because the OR will make a match for 13 digits a match for 8 digits one
THE SOLUTION IS:
Regex EAN8 = new Regex(#"\b\d{8}\b");
Regex EAN13 = new Regex(#"\d{13}\b");
PS FOR EDIT2: As someone said, problaly in the future i will end up finding EAN1234567890123 or EAN_1234567890123, these patterns wont work out, and I have no idea where to start searching for a pattern like this.
I'm doing a project where I need to take multiple EANs from a text.
I already have a validation class to see if they are valid or not.
And I can take the 13 digits one (but I think the pattern I'm using is not correct and will give problems sooner or later.
Example of a string: "OL‐120 112 82 Estuchado, fácil apertura. 8410032002279 227 24"
as you can see there is a valid EAN13 in the middle: "8410032002279"
I'm using this pattern:
Regex EAN13 = new Regex(#"\d{13}");
It gives me the EAN inside the string, but I think the correct pattern should be like this:
Regex EAN13 = new Regex(#"\d{13}$");
But when I use it it doesn't work. probably because the string doesn't end there.
I have a similar problem with the EAN of 8 digits, if i use this pattern:
Regex EAN8 = new Regex(#"\d{8}");
It gives me the 13 digit eans cut to 8...
What should I do to make both patterns work whatever the position of the EAN is in the string and for the 8 digit return only a real string with 8 digits and not one with more cut down to 8.
Thanks in advance
EDIT: Further Code to understand what I'm doing
Regex EAN = new Regex(#"\b(?:\d{8}|\d{13})\b");
using (StreamReader sr = new StreamReader(#"....txt"))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
Match m13 = EAN.Match(currentLine);
Match m8 = EAN.Match(currentLine);
if (m8.Success)
{
lista_EAN8.Add(m8.Value);
//string valido8 = new Ean8Validate().ValidateEan8(m8.Value);
//if (valido8 == m8.Value)
//{
// lista_EAN8.Add(m8.Value);
//}
}
if (m13.Success)
{
string valido13 = new Ean13Validate().ValidateEan13(m13.Value);
if (valido13 == m13.Value)
{
lista_EAN13.Add(m13.Value);
}
}
}
}
Like this it returns me the same values in list of 13 digit eans and list of 8 digits eans
ok looks like you want 2 different Regexs one for targeting only 8 digit matches and the other for targeting 13 digit matches
for matching of the 8 digit EANs use;
\b(?:\d{8})\b
for matching and for 13 digit EANs use;
\b(?:\d{13})\b
additionally is you want an options prefix of EAN(upper or lowercase) you can use;
for 8 digit
\b(?:[Ee][Aa][Nn])?(?:\d{8})\b
for 13 digit
\b(?:[Ee][Aa][Nn])?(?:\d{8})\b
for your example you want to modify the code so it read something like this.
Regex EAN8 = new Regex(#"\b(?:\d{8})\b");
Regex EAN13 = new Regex(#"\b(?:\d{13})\b");
using (StreamReader sr = new StreamReader(#"....txt"))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
Match m13 = EAN13.Match(currentLine);
Match m8 = EAN8.Match(currentLine);
if (m8.Success)
{
lista_EAN8.Add(m8.Value);
}
if (m13.Success)
{
lista_EAN13.Add(m13.Value);
}
}
}
now if we tweek the Regexs a little more we can extract just the number parts out of EAN numbers even when they are prefixed with EAN* or EAN_*
Regex EAN8 = new Regex(#"\b(?:[Ee][Aa][Nn]_?)?(\d{8})\b");
Regex EAN13 = new Regex(#"\b(?:[Ee][Aa][Nn]_?)?(\d{13})\b");
using (StreamReader sr = new StreamReader(#"....txt"))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
Match m13 = EAN13.Match(currentLine);
Match m8 = EAN8.Match(currentLine);
if (m8.Success)
{
lista_EAN8.Add(m8.Groups[1].Value);
}
if (m13.Success)
{
lista_EAN13.Add(m13.Groups[1].Value);
}
}
}
this will capture the number part while throwing away the EAN prefix
Use the below regex to match 8 or 13 digits. \b is a word boundary which matches between a word character and a non-word character. So it avoids matching 8 digit number in a 13 digit number.
\b(?:\d{8}|\d{13})\b
Try this regex string. \b = word boundary and the | makes sure that it will only match 8 or 13 and not some number in between:
\b\d{8}\b|\b\d{13}\b
If you want dob't allow unicode digit use character class instead shortcut \d ( it's much faster)
\b(?:[0-9]{8}|[0-9]{13})\b
I managed to concoct this:
\b(([Ee][Aa][Nn])?[_]?([0-9]{13}|[0-9]{8}))\b
This part ([Ee][Aa][Nn])? groups the case-insensitive sequence EAN and makes it optional with ?
Then [_]? makes the underscore optional. I added the square brackets for prettiness sake
The digits are identified using their character representation [0-9]{13} and [0-9]{8}
Everything is wrapped up in a \b( ... )\b block to identify the word boundary
The two EAN types are wrapped by parentheses and separated by an OR |
Below is a screenshot from http://regexpal.com/ showing the testing set and the matching.
Jorge, I must say I don't like repeating code, (or anything else for that matter :D ). I am therefore not very fond of the whole ([Ee][Aa][Nn])?[_]? appearing twice. Moreover if tomorrow you wish to look for EAN5 for example you must further copy it and the regexp becomes ever more ugly.
Here is what I had before the cleanup:
\b(([Ee][Aa][Nn])?[_]?[0-9]{13}|([Ee][Aa][Nn])?[_]?[0-9]{8})\b
Below is a screenshot from http://regexpal.com/ showing the testing set and the matching.
I want to validate a string based on a custom format: ___.___ or ___,___, 3 numbers followed by a dot or comma followed by 3 numbers (e.g. 123.456 or 123,456).
Currently, I have following code:
string InputText = "123.456"
bool result, result1, result2;
int test, test2;
result = Int32.TryParse(InputText.Substring(0, 3), out test);
result1 = (InputText[3] == '.' || InputText[3] == ',') ? true : false;
result2 = Int32.TryParse(InputText.Substring(4, 3), out test2);
if (result == false || result1 == false || result2 == false)
{
Console.WriteLine("Error! Wrong format.");
}
This works just fine, however, this seems rather inefficient and unnecessarily complex; is there an alternative to this?
Is there an alternative to this? Yes you can use Regex.IsMatch to do this.
String s = "123.456";
if (!Regex.IsMatch(s, #"^\d{3}[.,]\d{3}$")) {
Console.WriteLine("Error! Wrong format.");
}
Explanation:
^ # the beginning of the string
\d{3} # digits (0-9) (3 times)
[.,] # any character of: '.', ','
\d{3} # digits (0-9) (3 times)
$ # before an optional \n, and the end of the string
Pattern to validate 3 numbers followed by a dot or comma followed by 3 numbers is,
^\d{3}[,.]\d{3}$
DEMO
Aditional to Avinash answer if you want to capture the numbers matching the format you can use the following regex:
\b(\d{3}[.,]\d{3})\b
Working demo
I would like to replace from a number of 16 digits, it's 5th to 10th digit.
How can that be achieved with a regular expression (C#)?
The way to do it is to capture in the inner and outer portions separately, like this:
// Split into 2 groups of 5 digits and 1 of 6
string regex = "(\\d{5})(\\d{5})(\\d{6})";
// Insert ABCDEF in the middle of
// match 1 and match 3
string replaceRegex = "${1}ABCDE${3}";
string testString = "1234567890999999";
string result = Regex.Replace(testString, regex, replaceRegex);
// result = '12345ABCDE999999'
Why use a regular expression? If by "number of 16 digits", you mean a 16 character long string representation of a number, then you'd probably be better off just using substring.
string input = "0000567890000000";
var output = input.Substring(0, 4) + "222222" + input.Substring(10, 6);
Or did you mean you want to swap the 5th and 10th digits? Your question isn't very clear.
Use the regular expression (?<=^\d{4})\d{6}(?=\d{6}$) to achieve it without capture groups.
It looks for 6 consecutive digits (5th to 10th inclusively) that are preceded by the first 4 digits and the last 6 digits of the string.
Regex.Replace("1234567890123456", #"(?<=^\d{4})\d{6}(?=\d{6}$)", "replacement");
Got it...
by creating 3 capturing groups:
([\d]{5})([\d]{5})([\d]{6})
keep capturing group1 and 3 and replace group2 with stars (or whatever)
$1*****$3
C# code below
string resultString = null;
try {
resultString = Regex.Replace(subjectString, #"([\d]{5})([\d]{5})([\d]{6})", "$1*****$2", RegexOptions.Singleline);
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
I have a input which can be the following (Either one of these three):
1-8…in other words 1, 2,3,4,5,6,7,8
A-Z….in other words, A, B, C, D etc
01-98…in other words, 01,02,03,04 etc
I came up with this regex but it's not working not sure why:
#"[A-Z0-9][1-8]-
I am thinking to check for corner cases like just 0 and just 9 after regex check because regex check isn't validating this
Not sure I understand, but how about:
^(?:[A-Z]|[1-8]|0[1-9]|[1-8][0-9]|9[0-8])$
Explanation:
(?:...) is a group without capture.
| introduces an alternative
[A-Z] means one letter
[1-8] one digit between 1 and 8
0[1-9] a 0 followed by a digit between 1 and 9
[1-8][0-9] a digit between 1 and 8 followed by a digit between 1 and 9
9[0-8] 9 followed by a digit between 0 and 8
May be it is, depending on your real needs:
^(?:[A-Z]|[0-9]?[1-8])$
I think you may use this pattern
#"^([1-8A-Z]|0[1-9]|[1-9]{2})$"
What about ^([1-8]|([0-9][0-9])|[A-Z])$ ?
That will give a match for
A
8 (but not 9)
09
[1-8]{0,1}[A-Z]{0,1}\d{1,2}
matches all of the following
8A8 8B9 9 0 00
You can use following pattern:
^[1-8][A-Z](?:0[1-9]|[1-8][0-9]|9[0-8])$
^[1-8] - input should start with number 1-8
[A-Z] - then should be single letter A-Z
(0[1-9]|[1-8][0-9]|9[0-8])$ and it should end with two numbers which are 01-19 or 10-89 or 90-98
Test:
string pattern = #"^[1-8][A-Z](0[1-9]|[1-8][0-9]|9[0-8])$";
Regex regex = new Regex(pattern);
string[] valid = { "1A01", "8Z98" };
bool allMatch = valid.All(regex.IsMatch);
string[] invalid = { "0A01", "11A01", "1A1", "1A99", "1A00", "101", "1AA01" };
bool allNotMatch = !invalid.Any(regex.IsMatch);
I am trying to get a Regex that checks to make sure that a supplied int is 6 digits and it is not sequential nor contains all repeating digits whether in ascending or descending order. I don't really care if the regex returns a match for the non-allowed numbers, or returns a match of the original number if it is allowed.
So for example all of these numbers are what I would need to not pass validation with the regex:
123456
654321
069
456789
2435
444444
While numbers like these would pass:
044346
666605
042004
678853
Thanks.
EDIT: Appears regex is not appropriate for this. A lot of great answers and multiple are right, so I just went with who answered first, thank you all!
Regex may not be optimal for this, but it can be done with:
^
# fail if...
(?!
# repeating numbers
(\d) \1+ $
|
# sequential ascending
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5} \d $
|
# sequential descending
(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $
)
# match any other combinations of 6 digits
\d{6}
$
Use with /x flag or (?x) to preserve the readability.
You can also use the compact form (not recommended):
^(?!(\d)\1+$|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\d$)\d{6}$
Example usage (ideone):
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string re = #"(?x)
^
# fail if...
(?!
# repeating numbers
(\d) \1+ $
|
# sequential ascending
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5} \d $
|
# sequential descending
(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $
)
# match any other combinations of 6 digits
\d{6}
$
";
string[] numbers = { "102", "111111", "123456", "654321", "123455", "321123", "111112" };
foreach (var str in numbers)
{
Console.WriteLine(str);
Console.WriteLine(Regex.IsMatch(str, re) ? "\tMatched" : "\tFailed");
}
}
}
Output:
102
Failed
111111
Failed
123456
Failed
654321
Failed
123455
Matched
321123
Matched
111112
Matched
To be honest I don't think I got what you wanted, but following code works for your cases :)
var isMatch = Regex.IsMatch(input, "^[0-9]{6}$")
&& Regex.IsMatch(input, #"(([0-9]{1})\2+)")
&& input.Distinct().Count() > 1;
After several re-reading I think I got what you want :) See the following:
var isMatch = String.Join("", input.OrderBy(c => c)) != input
&& String.Join("", input.OrderByDescending(c => c)) != input
&& input.Distinct().Count() > 1
&& Regex.IsMatch(input, "^[0-9]{6}$");
The invalid strings are so little in number that you could just do this:
using System.Xml;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string input = "124032";
string[] invalid = {
"012345",
"123456",
// ...
"000000",
"111111",
// ...
};
if (Regex.IsMatch(input, #"^\d{6}$") && !invalid.Contains(input)) {
// ok
}
}
}
Just as a reference as to why you should NOT do this. Here's a regex that would satisfy your requirements -- it's a mess:
(?!123456)(\d)(((?!\1)\d{5})|((\d)(?!\1)\d{4})|((\d){2}(?!\1)\d{3})|((\d){3}(?!\1)\d{2})|((\d){4}(?!\1)\d))
where you must expand the (?!123456) for all 20 possible iterations of repeated digits. (20 = 10 possible starting digits * (one ascending + one descending))
You start off with the negative lookahead preventing the 20 sequential digits scenarios, grab a single digit, and then do checks that require (via a negative lookeahead) that at least one digit must be different from the first digit. If it passes this, it succeeds.
That's not a elegant solution but works!
/^[0]{6}|[1]{6}|[2]{6}|[3]{6}|[4]{6}|[5]{6}|[6]{6}|[7]{6}|[8]{6}|[9]{6}$/