tags:

views:

114

answers:

3
+1  Q: 

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", "");
}
A: 

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
philar
+1  A: 

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.

nixeagle
@nixeagle,+1 Thank you very much,it works great..
Harikrishna
@nixeagle, it does not work for OPTIDX 26FEB2009 NIFTY CE 2800. It matches with date here like 26.
Harikrishna
@Harikrishna Your original question gave very specific input criteria, this question is getting into problem specific details. For example if you know all "time" values are followed by spaces you can adjust the positive lookahead portion of the regex... that is `(?=[^0-9])` could be changed to `(?=\s)`. This causes a match to occur only when the "time" is followed by a space instead of a match occuring when the time is followed by anything but a number. Alternatively you can exclude all alphanumeric characters from matching with `(?=[^0-9a-zA-Z])`.
nixeagle
+2  A: 

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.

weismat