mor*_*eza 7 c# regex validation
如何通过正则表达式测试用户手机号码.伊朗手机有这样的数字系统:
091- --- ----
093[1-9] --- ----
Run Code Online (Sandbox Code Playgroud)
一些示例前缀:
0913894----
0937405----
0935673----
0912112----
Run Code Online (Sandbox Code Playgroud)
(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}
Run Code Online (Sandbox Code Playgroud)
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 +?? (???) ?? ?? ???"));
Run Code Online (Sandbox Code Playgroud)
支持所有这些选项
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
Run Code Online (Sandbox Code Playgroud)
甚至波斯数字
+?? (???) ?? ?? ???
Run Code Online (Sandbox Code Playgroud)
并且仅检测真正的伊朗运算符编号091x 092x 093x 094x
有关更多信息:https://gist.github.com/AliMD/6439187
根据维基页面http://en.wikipedia.org/wiki/Telephone_numbers_in_Iran#Mobile_phones,匹配项是:
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
Run Code Online (Sandbox Code Playgroud)
看起来像
(the specific sequence 09) (1 followed by 0-9 OR 3 followed by 1-9) (7 digits)
Run Code Online (Sandbox Code Playgroud)
假设你现在不关心破折号,这转化为
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
Run Code Online (Sandbox Code Playgroud)
((..|..)做 OR,[0-9]{7}说正好匹配 7 位数字,...)
如果您想在指定位置使用破折号:
09(1[0-9]|3[1-9])-?[0-9]{3}-?[0-9]{4}
Run Code Online (Sandbox Code Playgroud)
应该匹配
简单是生活的美化。试试这个:
^09[0|1|2|3][0-9]{8}$
//091 for Hamrahe-Aval Operator
//092 for Rightel Operator
//093 | 090 for Irancel Oprator
Run Code Online (Sandbox Code Playgroud)
这是我在项目中经常使用的 c# 中的扩展方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
像这样使用:
If(!txtMobileNumber.Text.IsValidMobileNumber())
{
throw new Exception("Mobile number is not in valid format !");
}
Run Code Online (Sandbox Code Playgroud)