Mithun S
Mithun S

Reputation: 418

Javascript Regex Pattern for Two Decimal Places

pattern = new RegExp('([0-9]+([.][0-9]{1,2})?|[.][0-9]{1,2})');

it should accept 00.00, 0.0, 00.25, 00.36, 00.56,, 222.25, 222.25, 2222.25,

should not accept 000.25, 0000.25

Upvotes: 2

Views: 252

Answers (4)

The fourth bird
The fourth bird

Reputation: 163207

If your value can not start with a zero, you could use an alternation:

^(?:(?:0{1,2}|[1-9]\d*)?\.\d{1,2}|[1-9]\d*)$

That will match:

  • ^ Start of the string
  • (?: Non capturing group
    • (?: Non capturing group
      • `0{1,2}|[1-9]\d* Match a zero 1-2 times OR digit 1-9 and 0+ times a digit
    • )? Close on capturing group and make it optional
    • \.\d{1,2} Match a dot and 1-2 digits
    • | Or
    • [1-9]\d* Match digit 1-9 followed by 0+ times a digit
  • ) Close non capturing group
  • $ End of the string

Regex101 demo

If you do want to allow a leading zero, you could add matching 0+ times a zero 0* before the second alternation:

^(?:(?:0{1,2}|0*[1-9]\d*)?\.\d{1,2}|[1-9]\d*)$

Regex101 demo

Upvotes: 1

Neb
Neb

Reputation: 2280

Use this:

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

Explanation:

Before the dot \., It accepts either of the two (|):

  • ^[0-9] the code starts with any number between 0 and 9
  • [1-9]+ then, there are as many digits between 1 and 9 as you wants

or:

  • ^0{0,2} the code starts with at most two zeros

Upvotes: 0

thb
thb

Reputation: 14434

Try this:

(?<![0-9.])((?:[0-9]{1,2}|[1-9][0-9]*)(?:[.][0-9]{1,2})?)(?![0-9.])

Note the anchors (?<!) and (?!). You can omit the anchors if you wish but the anchors will let your pattern match even if the line contains noise other than the number. The (?<!X) insists that X not precede the match. The (?!X) insists that X not follow the match.

[If you wanted to insist that X did indeed precede and/or follow, then you would instead anchor with (?<=X) and/or (?=X).]

Based on the tenor of your examples, my solution assumes that these are acceptable: 01.23; 00.23; 1.23. It assumes that these are not acceptable: 011.23; 1.234.

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can use this

^(?:(?!0{3,}).*)\.\d+$
  • ^ - Start of string.
  • (?:(?!0{3,}).*) -Condition to avoid more than 2 zeros at start.
  • \.\d+ - Matches . followed by one or more digit.
  • $ - End of string

Demo

Upvotes: 1

Related Questions