Quick and Easy Currency Extractor

I have fallen in love with Regular Expressions over the past few months. Over the weekend I replaced some moderately complicated parsing code in an older application with a Regular Expression and found another quick use for one this morning, extracting a currency value.

So here was my problem, I have an application that displays the cost of an item in several ways, the common $##.## or $##.##/[time frame] and so on. I needed to just grab the actual amount to store in my database. A few years ago I would have thought ‘Oh great here go 4-5 hours of my life’. Not anymore today I spent 5 minutes thinking about and testing a simple pattern to extract just the dollar amount.

Potential Text to Extract From

Oranges $4.99/lb
Milk $2.69/quart
Rent $1000/month
Honda Accord $21,000.00

   

Public

Function

ExtractDollarAmount(

ByVal

sDollar

As

String

)

As

Double

 

       

Dim

r

As

New

Regex(

"(\d+\.{1}\d{1,2})"

)

 

       

For

Each

m

As

Match

In

r.Matches(sDollar)

           

Try

               

Return

Convert.ToDouble(m.Value)

           

Catch

ex

As

FormatException

               

'Return -1D

               

Throw

           

Catch

exo

As

OverflowException

               

'Return -2D

               

Throw

           

End

Try

 

       

Next

 

   

End

Function

C#:

       

public

double

ExtractDollarAmount(

string

sDollar)

        {

           

Regex

r =

new

Regex

(

"(\\d+\\.{1}\\d{1,2})"

);

           

foreach

(

Match

m

in

r.Matches(sDollar))

            {

               

try

                {

                   

return

Convert

.ToDouble(m.Value);

                }

               

catch

(

FormatException

ex)

                {

                   

throw

;

                }

               

catch

(

OverflowException

exo)

                {

                   

throw

;

                }

            }

           

return

-1D;

        }

This method is real simple as well as the expression. It does have some faults, but like I said it was 5 minutes of time, but solved a fairly common need I think many of us have. I added this method to the base Page class of this application, but will most likely place it some sort of utility class as I complete abstracting my core framework.
If you have any suggestions on making this a stronger pattern, please feel free to let me know. I am going to see about posting this on RegExLib.com later today.

Share This Article With Your Friends!

We use cookies to give you the best experience possible. By continuing, we'll assume you're cool with our cookie policy.

Install Love2Dev for quick, easy access from your homescreen or start menu.

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel