Jonathan
Jonathan

Reputation: 2358

Regular Expression for a range >= 0 but less than 1000

I am busy working on this and thought I would put it our there.

It must be a number with a maximum of 3 units and maximum of 5 decimal places etc

Valid

Invalid

EDIT It needs to be greater than or equal to zero.

Upvotes: 6

Views: 19351

Answers (5)

William Humphries
William Humphries

Reputation: 568

Built off of answer by @ohaal above for currency $0.00 - $999.99

Regex $0.00 - $999.99

(\$(?!\d{1,3},\d{1,3})(?!\d{4})\d{1,3}(?!\d{1,3}\.\d\D)(?:\.\d{2,5})?)(?!\.)(?!,\d{3})

Upvotes: 0

ohaal
ohaal

Reputation: 5268

In light of your recent changes to the question, here is an updated regex which will match all >= 0 and <1000

^\d{1,3}(?:\.\d{1,5})?$
  ^\___/ \/ ^\/\___/ |
  |  ^   ^  | |  |   `- Previous is optional (group of dot and minimum 1 number between 0-9 and optionally 4 extra numbers between 0-9)
  |  |   |  | |  `- Match 1-5 instances of previous (single number 0-9)
  |  |   |  | `- Match a single number 0-9
  |  |   |  `- The dot between the 1-3 first number(s) and the 1-5 last number(s).
  |  |   `- This round bracket should not create a backreference
  |  `- Match 1-3 instances of previous (single number 0-9)
  `- Match a single number 0-9

^ is start of line, $ is end of line.

Valid

  • 999.99999
  • 999.0
  • 999
  • 99.9
  • 99.0
  • 99
  • 9
  • 0.1
  • 0.01
  • 0.001
  • 0.0001
  • 0.99999
  • 0.01234
  • 0.00123
  • 0.00012
  • 0.00001
  • 0.0
  • 0.00000
  • 0
  • 000.00000
  • 000

Invalid

  • -0.1
  • 999.123456
  • AAA
  • AAA.99999
  • 0.
  • .123

Upvotes: 14

Nikodemus RIP
Nikodemus RIP

Reputation: 1379

Check out http://www.regular-expressions.info/numericranges.html there's a lot of examples about numbers and discussions about pro- and cons of different approaches.

Upvotes: 0

Ed Guiness
Ed Guiness

Reputation: 35267

/\d{1,3}(\.\d{1,5})?\b/  # the boundary \b prevents matching numbers after the max of 5

Edit: A quick search shows that as usual, there's a CPAN module for this.

Regexp::Common::number

@ohaal correctly points out that this will also match 0, which is invalid. I suggest a combination of this regex and a test that the matched value is greater than 0.

Also see http://www.perlmonks.org/?node_id=614452

Upvotes: 1

SNAG
SNAG

Reputation: 2113

   ^([0-9].[0-9]{0,5}|[1-9][0-9]{0,2}.{0,1}[0-9]{0,5})$

Accepted 999.99999 99.9 9 0.99999

Rejected -0.1 999.123456 AAA AAA.99999 0

Upvotes: 1

Related Questions