Link to home
Start Free TrialLog in
Avatar of steve_mick972
steve_mick972

asked on

Regex for match number.

I am trying to process a number. I would like to check if the number is a valid currency .

If the user enters

  Input                         should return
-----------------------------------------------
  $50000                         50000  
  $50,000                        50000  
  $50,000.12                   50000.12  
  $50000.23                    50000.23
 
  USD 50,000                  50000

 After it matches a regex patter for currency then i use a  Convert.ToDouble

Any ideas?


Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Yurich
Yurich
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As a general rule, validating numbers with regular expressions isn't a very good idea. There are a lot of issues  
Shoot...sorry about that, accidentally submitted in the middle there. Let me try that again:

As a general rule, validating numbers with regular expressions isn't a very good idea. There are a lot of issues to consider, many of which are not easy to capture in a regular expression. For example, the regular expression Yurich gives above will allow strings like "1.2.3.4," which will cause Convert.ToDouble() to throw an exception, which I assume is what you're trying to avoid by doing the validation first. Instead of validating with a regular expression and then using Convert.ToDouble(), you should consider using Double.TryParse() (documented at http://msdn2.microsoft.com/library/8w0x0ctx(en-us,vs.80).aspx), which will attempt to parse a string into a double and return false if it fails, instead of throwing an exception. This is much more reliable and safer than trying to validate a number with a regular expression.
static double F(string S) {
            string[] Currencies = new string[] { "$", "USD" };
            string AuxStr = S.Trim();
            double RetVal = -1;

            foreach (string Currency in Currencies) {
                if (AuxStr.StartsWith(Currency)) {
                    AuxStr = AuxStr.Substring(Currency.Length).Trim();
                    break;
                }
            }
            try {
                RetVal = Convert.ToDouble(AuxStr);
            } catch (FormatException) { }
           
            return RetVal;
        }
Really no way!

How can you accept a solution that admits an aberration such as ".,3.$,5$.9,$0.$," as valid input?

That solution doesn't do ANY validity check on the format of the input as a unit. It merely restricts the valid input characters, but imposes no structure or order to them. There isn't even any numeric conversion done, so the final output for the string I quoted above gives a result of ".3.5.90.". Now what's that good for?

Also, wasn't it a requirement that the function returned 50000 for 'USD 50,000'?