BeeGees
BeeGees

Reputation: 481

Why is Regex Group Extraction Giving Wrong Answer?

I am trying to get the Number for an Integer number (No Decimal exist), or the number part before the Decimal Point for a Decimal Number.

The example below should give 12345 as the answer. But it is giving it as 1234 (eating the 5 out)

            string isDecimalTypeNumbers = @"^(?<wholeNumberPart>[0-9]*)\.?[0-9]+?$";
            Regex pattern = new Regex(isDecimalTypeNumbers);
            Match match = pattern.Match("12345");
            if (match.Success)
            {
                string wholeNumberPartWithoutPlusMinusSign = match.Groups["wholeNumberPart"].Value;
                MessageBox.Show(wholeNumberPartWithoutPlusMinusSign);
            }

Upvotes: 0

Views: 65

Answers (2)

Xiaoy312
Xiaoy312

Reputation: 14477

  • The decimal separator (\.?) is optional, so it may not match.
  • The fractional part ([0-9]+?) is not optional, but lazy, so it will still try to match.

So, what could happen is 1234 is consumed by the whole number part, and \.? doesnt match, but 5 is consumed by the fractional part.

You should make the decimal separator and the fractional part into one optional group:

@"^(?<wholeNumberPart>[0-9]*)(\.[0-9]+)?$"

Upvotes: 1

openshac
openshac

Reputation: 5155

^(?<wholeNumberPart>[0-9]*)

captures the first part of the number

\.?

captures the decimal point if it exists

[0-9]+?$

captures the last number regardless of whether there is a decimal point

So as you can see the last bit captures the 5 leaving only 1234 as the wholeNumberPart.

I think this explains why the regex group extraction is giving you the wrong answer of 1234

Upvotes: 1

Related Questions