Solved

Conditional Regex.Replace

Posted on 2006-06-26
4
1,058 Views
Last Modified: 2009-07-29
This article (http://www.experts-exchange.com/Programming/Q_21668801.html?query=format+phone+number+with+regex.replace&clearTAFilter=true) showed me how to use Regex.Replace to format a string as a phonenumber, which for the most part is great.  However, if there is no extension in the phone number I don't want there to be a trailing hiphen.  How do I adjust the regular expression so that the last hipen between the phone number suffix and the extension is only used if there is an extension present in the phone number?

Here's what I'm using:
string phoneNumber = "1234567890"
ResultString = Regex.Replace(phoneNumber, "^(\\d{3})(\\d{3})(\\d{4})(\\d*)$", "($1) $2-$3-$4");

Output:  "(123) 456-7890-"

I want the output to look like "(123) 456-7890"
or like "(123) 456-7890-1234" if an extesion exists.

Thanks in advance
0
Comment
Question by:orrin77
  • 2
  • 2
4 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 16989061
Hi orrin77;

The replacement string is very limited in what you can do. Because of that limitation to do what you want is to do the following.

using System.Text.RegularExpressions;

      string phoneNumber = "1234567890";
      string ResultString = "";
      string pattern = @"^(\d{3})(\d{3})(\d{4})(\d*)$";
      string replace1 = "($1) $2-$3";
      string replace2 = "($1) $2-$3-$4";
      string repStr = "";

      // Check to see if phone number has an extension.
      if( phoneNumber.Length > 10 )
            repStr = replace2;            // Has extension.
      else
            repStr = replace1;            // Does not have extension.

      // Reformat the telephone number
      ResultString = Regex.Replace(phoneNumber,
            pattern, repStr);

      MessageBox.Show( ResultString );


Fernando
0
 

Author Comment

by:orrin77
ID: 16995510
Right, but what about the regular expression itself?  Can I use a look ahead, or something like that to test a condition?
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 16995762
The problem is not in the Regular Expression to do the search the problem is in the replacement sting and what you can use for it. These are the only meta characters that can be used in the replacement string.

$number          Substitutes the last substring matched by group number number (decimal).
${name}          Substitutes the last substring matched by a (?<name> ) group.
$$            Substitutes a single "$" literal.
$&            Substitutes a copy of the entire match itself.
$`             Substitutes all the text of the input string before the match.
$'             Substitutes all the text of the input string after the match.
$+            Substitutes the last group captured.
$_            Substitutes the entire input string.

All other character are used as themselves and non of the above will let you do a look ahead in the replacement string.
0
 

Author Comment

by:orrin77
ID: 16997097
Thank you Fernando
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now