lintmouse
lintmouse

Reputation: 5119

Why doesn't this number regex (with alternations) match as expected?

I am trying to match the following strings:

9
9.
9.5
.5

This is what I've produced so far to accomplish this:

(?<acreage>(?(\d+)((\.\d*)?)|(\.\d+)))

When I pass in 9.5, it returns NULL and .5 for acreage. I need it to pass back 9.5. What am I doing wrong?

Upvotes: 1

Views: 49

Answers (2)

burning_LEGION
burning_LEGION

Reputation: 13450

use this regular expression

^(?=\.?\d+\.?\d*)\d*\.?\d*$

or

^(\d+\.\d*)|(\d*\.\d+)|(\d+)$

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545608

So you have four situations:

  1. Match something like x
  2. Match something like x.y
  3. Match something like x.
  4. Match something like .y

So here you go:

\d+\.\d+|\d+\.?|\.d+

You can get rid of either of the last two possibilities by making digits in the first group optional, but not both. For instance:

\d*\.\d+|\d+\.?

Or, with a match group:

(?<acreage>\d*\.\d+|\d+\.?)

Upvotes: 2

Related Questions