Need help with a regular expression
I am trying to use a regular expression like this:
string Size= "10.5M";
Match m = null;
if ((m = (new Regex(@"(\d)([M开发者_StackOverflow中文版GTP%]?)", 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
A \d
doesn't match the '.'. Use [0-9]+(\.[0-9]+)?
instead.
The \d
character class matches a digit character. To match a number with a fractional part, as in your example you will need to:
- Match more than one digit: apply the
+
quantifier to\d
; - Match the dot; since a dot has a special meaning (it matches any character), you need to escape it with a
\
; - Match some more digits;
- Maybe make the dot and the fractional part optional, using the
?
(zero or one) and*
(zero or more) quantifiers, respectively.
A regular expression like this one may suit your needs:
(\d+\.?\d*)([MGTP%]?)
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.
精彩评论