Terry  H
Terry H

Reputation: 347

Regex for whole numbers or numbers with quarter decimal

I need a regex that only allows for whole numbers or numbers with a quarter decimal.

So far I have this, however this code /[^.]+\.25|[^.]+\.50|[^.]+\.75|[^.]+\.00/ forces user to type a number with a decimal. I'm looking for something more flexible.

Valid

0
0.
.25
.5
.75
3
1.

1.00 5.0 4.25 8.50 8.75

Invalid

1.2
.3
.
empty space

Upvotes: 0

Views: 996

Answers (2)

The fourth bird
The fourth bird

Reputation: 163237

You might use an alternation to match either an optional digit followed by a dot the quarter decimal part or match one or more digits followed by an optional dot.

^(?:\d*\.(?:[27]5|50?|00?)|\d+\.?)$

Explanation

  • (?: Non capturing group
    • \d*\. Match zero or more times a digit followed by a dot
    • (?:[27]5|50?|00?) Non capturing group which matches 25, 75, 50, 5, 0 or 00
    • | Or
    • \d+\.? Match one or more times a digit followed by an optional dot
  • ) Close non capturing group
  • $ Assert the end of the string

Upvotes: 2

melpomene
melpomene

Reputation: 85767

Here's one way:

/\A (?= \.? [0-9] ) [0-9]* (?: \. (?: [05]0? | [27]5 )? )? \z/x

Or with comments:

/
  \A  # beginning of string

  (?=  # look-ahead
    \.?    # a dot (optional)
    [0-9]  # a digit
  )
  # ^ this part ensures that there is at least one digit in the string.
  # in the following regex all parts are optional.

  [0-9]*  # the integer part: 0 or more digits
  (?:  # a group: the decimal part
    \.  # a dot
    (?:  # another group for digits after the decimal point
      [05]0?  # match 0 or 5, optionally followed by 0 (0, 00, 5, 50)
      |
      [27]5   # ... or 2 or 7, followed by 5 (25, 75)
    )?  # this part is optional
  )?  # ... actually, the whole decimal part is optional

  \z  # end of string
/x

It's a bit tricky because all parts of the number are optional in some way:

  • .25 is valid, so the integer part is optional
  • 0 is valid, so the decimal point and following digits are optional
  • 0. is valid, so the decimal digits are optional

The main regex is written in a way that makes all parts optional, but there's a look-ahead assertion before it to make sure that the whole string is not empty or just ..

Upvotes: 0

Related Questions