Reputation: 4305
(\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
Reputation: 2881
For all price format
and concatenate with other string
1.234,56asdfdasfdsaf
and all formats
Regex
@"((?<=\s)|^)[-+]?((\d{1,3}([,\s.']\d{3})*)|\d+)([.,/-]\d+)?((?=\s)|$)"
Upvotes: 0
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
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
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