简体   繁体   中英

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.

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

Online demo

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM