Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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

  • 999.99999
  • 99.9
  • 9
  • 0.99999
  • 0

Invalid

  • -0.1
  • 999.123456
  • AAA
  • AAA.99999

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

like image 470
Jonathan Avatar asked Feb 23 '12 10:02

Jonathan


People also ask

How do you specify a range in regex?

Ranges of characters can be indicated by giving two characters and separating them by a '-', for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59.

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

Which regex means zero or more occurrences?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used. A regular expression followed by a plus sign ( + ) matches one or more occurrences of the one-character regular expression.

What is regex for numbers?

The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.


1 Answers

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
like image 98
13 revs Avatar answered Dec 05 '22 18:12

13 revs