Reputation: 49
I am trying to use a regular expression like this:
string Size= "10.5M";
Match m = null;
if ((m = (new Regex(@"(\d)([MGTP%]?)", RegexOptions.IgnoreCase).Match(Size))).Success)
{
Size = m.Groups[1].ToString();
if (m.Groups.Count > 1)
SizeUnit = m.Groups[2].ToString(); // if not given, SizeUnit is percentage
}
But when I pass the value, Size shows as 10, and SizeUnit as "" instead of the expected Size = 10.5 and SizeUnit = M
Upvotes: 1
Views: 129
Reputation: 32936
your problem is that your expression only currently matches on a digit and not on the decimal point and following digits. This would be better I think
if ((m = (new Regex(@"(\d*\.?\d*)([MGTP%]?)", RegexOptions.IgnoreCase).Match(Size))).Success)
{
Size = m.Groups[1].ToString();
if (m.Groups.Count > 1)
SizeUnit = m.Groups[2].ToString(); // if not given, SizeUnit is percentage
}
which will match at least 0 or more digits followed by a single '.' followed by zero or more other digits.
Upvotes: 0
Reputation: 234404
The \d
character class matches a digit character. To match a number with a fractional part, as in your example you will need to:
+
quantifier to \d
;\
;?
(zero or one) and *
(zero or more) quantifiers, respectively.A regular expression like this one may suit your needs:
(\d+\.?\d*)([MGTP%]?)
Upvotes: 1