Excel Dev
Excel Dev

Reputation: 49

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)([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

Answers (3)

Sam Holder
Sam Holder

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

Hans Kesting
Hans Kesting

Reputation: 39274

A \d doesn't match the '.'. Use [0-9]+(\.[0-9]+)? instead.

Upvotes: 4

R. Martinho Fernandes
R. Martinho Fernandes

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:

  • 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%]?)

Upvotes: 1

Related Questions