[英]Phone number regex extraction from formatted string
鉴于电话号码均采用以下格式:
(999) 999-9999 Ext.9999"
我想将所有内容返回第二个空格,例如:
(999) 999-9999
有任何想法吗?
如果您的字符串在s中:
string s = "(999) 999-9999 Ext.9999";
string number = s.Split(" Ext")[0];
如果要完美匹配,可以使用以下表达式:
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);
}
不要使用正则表达式。 使用Split()
。 然后将前两个元素重新连接在一起。
其中s
包含完整的字符串。 如果忠实地“已在此格式” 正是 ,那么你可以只取前14个字符:
string number = s.SubString(0, 14);
或更灵活,更安全:
var idx = s.IndexOf(" Ext");
//good idea to check if idx == -1
string number = s.SubString(0, idx);
看看这个:
string s = "(999) 999-9999 Ext.9999";
string phonenumber1 = Regex.Replace(s, @"(?i)\s*ext\.\d+", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.