1

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

1
  • This one might work: (\d+\.\d+)([MGTP%]?) Commented Mar 18, 2011 at 10:52

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

3 Comments

You could use * instead of mixing + and ?.
How do you know 10. is not valid and .5 is?
you're right, I could use *. And I don't know what is valid and what isn't. I assumed from the example it was a number that was going to be expected, but was just trying to point out what it would and wouldn't do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.