[英]Phone number regex extraction from formatted string
Given the phone numbers are all on this format: 鉴于电话号码均采用以下格式:
(999) 999-9999 Ext.9999"
I want to return everything to the second space, eg: 我想将所有内容返回第二个空格,例如:
(999) 999-9999
Any ideas? 有任何想法吗?
if your string is in s: 如果您的字符串在s中:
string s = "(999) 999-9999 Ext.9999";
string number = s.Split(" Ext")[0];
If you want a perfect match, you can use this expression: 如果要完美匹配,可以使用以下表达式:
string s = "(999) 999-9999 Ext.9999";
Match m = Regex.Match(s, @"(?<nr>\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})");
if (m.Groups["nr"].Success)
{
Console.WriteLine(m.Groups["nr"].Value);
}
Where s
contains the full sting. 其中
s
包含完整的字符串。 If truely "all on this format" exactly , then you could just take the first 14 characters: 如果忠实地“已在此格式” 正是 ,那么你可以只取前14个字符:
string number = s.SubString(0, 14);
Or a bit more flexible, and safer: 或更灵活,更安全:
var idx = s.IndexOf(" Ext");
//good idea to check if idx == -1
string number = s.SubString(0, idx);
Check out this one: 看看这个:
string s = "(999) 999-9999 Ext.9999";
string phonenumber1 = Regex.Replace(s, @"(?i)\s*ext\.\d+", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.