0

Given the phone numbers are all on this format:

(999) 999-9999 Ext.9999"

I want to return everything to the second space, e.g.:

(999) 999-9999

Any ideas?

1
  • Is this valid the valid scenerio '(999) 999-9999 ext.9999' i.e., ext is in small letters ? Commented Nov 19, 2012 at 7:01

5 Answers 5

5

if your string is in s:

   string s = "(999) 999-9999 Ext.9999";
   string number = s.Split(" Ext")[0];
Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

Comments

1

Don't use a regular expression. Use Split(). Then concatenate the first two elements back together.

1 Comment

Maybe. Rather harsh if so. I was the first answer and supplied the same answer as the accepted answer. Sans code sample. Not familiar enough with C#.
1

Where s contains the full sting. If truely "all on this format" exactly, then you could just take the first 14 characters:

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);

Comments

0

Check out this one:

    string s = "(999) 999-9999 Ext.9999";
    string phonenumber1 = Regex.Replace(s, @"(?i)\s*ext\.\d+", "");

3 Comments

Why remove what you don't want? Isn't it better to specify what you do want?
@WouterH, do you think a shorter pattern will be inefficient ? also the unnecessary part was less than the required part.
I have no problems with efficiency... Think about it: if you have a pattern that extracts the required part, you can reuse it on any text of any length surrounded by anything. So it's more future proof and cleaner for future developers that will need to work on that code one day without knowing the exact input. Why is he stripping that 'ext.' again? Oh he wants the phone number, not very clear isn't it? The same applies for the .Split methods proposed here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.