Harikrishna
Harikrishna

Reputation: 4305

Regex for price

(\d+(?:\.\d+)?)\D*$ - this regex extracts price from any string with decimal point, but I want to extract decimal point only when there is something but not zero like when there is 300.50 or 300.25 then decimal point should be extracted but if there is 300.00 then the decimal point should not be extracted, what to do ?

This is ok, or any better solution is there ?

Match match = Regex.Match(cellRecord, @"(\d+(?:\.\d+)?)\D*$");
price = match.Groups[1].Value.ToString().Trim();
if (price.Substring(price.Length - 3, 3) == ".00")
{
    price = price.Replace(".00", "");
}

Upvotes: 1

Views: 4280

Answers (4)

Aljohn Yamaro
Aljohn Yamaro

Reputation: 2881

For all price format

  • 1,234.56 -- United States
  • 1.234,56 -- German
  • 1'234.56 -- Switzerland
  • 1 234,56 -- French
  • 1,234/56 -- Persian (Iran)
  • 1 234-56 -- Kazakhstan
  • 1 234.56 -- Estonia

and concatenate with other string

  • 1 234.56Adfsafdasfasdf
  • 1 234-56fasdfsadf
  • 1.234,56asdfdasfdsaf

  • and all formats

Regex

@"((?<=\s)|^)[-+]?((\d{1,3}([,\s.']\d{3})*)|\d+)([.,/-]\d+)?((?=\s)|$)"

Upvotes: 0

Philar
Philar

Reputation: 3897

This regex should work for the inputs you have mentioned. Please see output below.

 "\b(\d+(?:\.(?:[^0]\d|\d[^0]))?)\b"

Works as follows

input OPTIDX 26FEB2009 NIFTY CE 2800
output 2800

input 123.00
output 123

input 123.06
output 123.06

input 123.50
output 123.50

Upvotes: 0

nixeagle
nixeagle

Reputation: 1002

Assuming by better way you mean "can a regex do this on its own?" then:

([0-9]+(?:\.(?:[1-9][1-9]|[0-9][1-9]|[1-9][0-9]))?)(?=[^0-9])

will place matches in the first regex grouping. What this regex is doing is matching any number and then for the "cents" portion allowing any combination of numbers except 00. Note also that this matches values with two digits in the "cents" portion.

Note that this regex uses [0-9] instead of \d to make it a little clearer which digits are acceptable.

Edit: Please note this regex was tested in GNU/Emacs and not C#, but I don't think there is any difference in this case.

Edit: I made a small mistake where the regex matched '300.' not '300', adjusted regex only groups the period if there is a match.

Upvotes: 2

weismat
weismat

Reputation: 7411

I would also investigate using Double.Parse with the right culture info - this is usally a lot simpler and more stable than using your own regular expression.

Upvotes: 3

Related Questions