SamJolly SamJolly -4 years ago 86
C# Question

How to produce a negative decimal from a string using Regex?

I need to create a negative decimal from a string ie:

Currently I have code that works well for positive decimal as such:

var decimalList = Regex.Split("£100.00", @"[^0-9\.]+").Where(c => c != "." && c.Trim() != "");
decimal decimalValue = decimal.Parse(decimalList.First());


Which results in 100.00

var decimalList = Regex.Split("X-100.00X", @"[^0-9\.]+").Where(c => c != "." && c.Trim() != "");
decimal decimalValue = decimal.Parse(decimalList.First());


Which should result in -100.00 which is the point of this question.

How do I change the Regex to cope with negative values ie: "-1.2" and maintain the negative in the resulting decimal.

Thanks.

Answer Source

I think a matching approach would be easier here. A pattern to match a float/integer-like values is -?[0-9]*\.?[0-9]+, and with Regex.Match, you can extract the first occurrence of the pattern in a string. Then, just parse the value found:

var s = "X-100.00X";
var match = Regex.Match(s, @"-?[0-9]*\.?[0-9]+");
if (match.Success) {
    decimal decimalValue = decimal.Parse(match.Value);
    Console.Write(decimalValue);
}

See the C# demo.

Pattern details:

  • -? - an optional -
  • [0-9]* - 0+ digits
  • \.? - an optional .
  • [0-9]+ - 1 or more digits.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download