Shanmugaraja_K
Shanmugaraja_K

Reputation: 2382

How to match exact digits count by using regex in javascript

I need to find 3 digits after all dots (.). If I give input "1.22.222", it should return false. If I give "1.222.222" then it should return true. I have tried the below regex but it didn't work.

var reg1 = new RegExp("\\.\\d{3}");
var reg2 = new RegExp("\\.\\d{3,3}");
reg1.test("1.22.222") // returns true, but i need to return false.

How to resolve this.

Upvotes: 0

Views: 96

Answers (4)

undg
undg

Reputation: 825

var reg = new RegExp("^\d(\.\d{3})")

var out = reg.test("1.222.222") console.log(out) // true

var out = reg.test("1.22.222") console.log(out) // false

var out = reg.test("1.222.22") console.log(out) // false

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163277

Maybe you could use ^[^\.]+(?:\.\d{3})+$

This will match

^         # From the beginning of the string
[^\.]+    # match NOT a dot one or more times
(?:       # A non capturing group
  \.\d{3} # Match a dot and 3 digits
)         # Close non capturing group and repeat one or more times
$         # The end of the string

Upvotes: 1

undg
undg

Reputation: 825

It need to begin with something before dot, and end with 3 digits before dot

var reg = new RegExp("^\\d(\\.\\d{3})+$");
var out = reg.test("1.222.222")
console.log(out) // true
var out = reg.test("1.22.222")
console.log(out) // false
var out = reg.test("1.222.22")
console.log(out) // false

Upvotes: -2

Mohammad Javad Noori
Mohammad Javad Noori

Reputation: 1217

use this ^\d(\.\d{3})+$

Online demo

Upvotes: 3

Related Questions