Monday, 9 September 2013

Regex - The minus sign is not getting caught when processing float numbers in C#

Regex - The minus sign is not getting caught when processing float numbers
in C#

I'm trying to extract 2 numbers from the following string (named interim):
"location" : { "lat" : 42.3875968, "lng" : -71.0994968 },
Here's the code I use in C#:
// define a regex for float numbers
Regex rx = new Regex(@"\b-?[0-9]*\.?[0-9]+\b", RegexOptions.Compiled |
RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rx.Matches(interim);
return matches[0].ToString() + ", " + matches[1].ToString();
The return is "42.3875968, 71.0994968", without the minus sign for the
second float number.
I debugged into the code that can confirm that the "-" is not in the
result of matches var.
I've also tested the following regexes, for the same result:
[-+]?[0-9]*\.?[0-9]+
(-|+)?[0-9]*\.?[0-9]+
(-|\+)?[0-9]*\.?[0-9]+
(-\+)?[0-9]*\.?[0-9]+
Any one have an idea why this doesn't work?
Thanks, Mylo

No comments:

Post a Comment