public static List<Double> ParseDoubleValues(string text,
int parseCount = -1)
{
// Full pattern:
// (((-?)(\d{1,3}(,\d{3})+)|(-?)(\d)+)(\.(\d)*)?)|((-)?\.(\d)+)
List<Double> results = new List<Double>();
if (text == null) { return results; }
// Optional negative sign and one or more digits
// Valid: "1234", "-1234", "0", "-0"
string signedIntegerNoCommas = @"(-?)(\d)+";
// Optional negative sign and digits grouped by commas
// Valid: "1,234", "-1,234", "1,234,567"
// INVALID: "12,34" <-- does not fit "normal" comma pattern
string signedIntegerCommas = @"(-?)(\d{1,3}(,\d{3})+)";
string or = @"|";
// Optional decimal point and digits
// Valid: ".123", ".0", "", ".12345", "."
string optionalUnsignedDecimalAndTrailingNumbers = @"(\.(\d)*)?";
// Optional negative sign, decimal point and at least one digit
// Valid: "-.12", ".123"
// INVALID: "", ".", "-."
string requiredSignedDecimalAndTrailingNumbers = @"((-)?\.(\d)+)";
string pattern = @"";
// Allow a signed integer with or without commas
// and an optional decimal portion
pattern += @"(" + signedIntegerCommas + or + signedIntegerNoCommas
+ @")" + optionalUnsignedDecimalAndTrailingNumbers;
// OR allow just a decimal portion (with or without sign)
pattern = @"(" + pattern + @")" + or
+ requiredSignedDecimalAndTrailingNumbers;
List<string> matches = GetMultipleRegExMatches(text, pattern);
int matchIndex = 0;
foreach (string match in matches)
{
// If the user supplied a max number of
// doubles to parse, check to make sure we don't exceed it
if (parseCount > 0)
{
if (matchIndex + 1 > parseCount) break;
}
try
{
// Get rid of any commas before converting
results.Add(Convert.ToDouble(match.Replace(",", "")));
}
catch
{
string msg = "Unable to convert {0} to a double";
Debug.WriteLine(string.Format(msg, match));
}
matchIndex += 1;
}
return results;
}