简体   繁体   English

从格式化的字符串中提取电话号码正则表达式

[英]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);
}

Don't use a regular expression. 不要使用正则表达式。 Use Split() . 使用Split() Then concatenate the first two elements back together. 然后将前两个元素重新连接在一起。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM