简体   繁体   中英

Cannot find errors of the regular expression

I am making a version filter which accepts user input as a key. This filter needs to have a check mechanism to disable illegal version input. My legal version is something like 1.2.3.4 , so I make a regexp bellow,

RegExp('^(\d+\.)*(\d+)$').test('1.2.3.4')

My original plan was that ^(\\d+\\.) means something like 123., 1. (\\d+)$ means a chunk full of digits.

But it always returned false, confusing me; I am not sure what to do to further correct it.

Any ideas or suggestions are welcome.

I think you should use the following regex pattern:

^\d+(\.\d+)*$

This would match a standalone single number, eg 5 , or a number followed by a dot and another number, eg 1.5 , and so on. The trick is to make the entire .NUMBER term optional.

 // positive cases console.log(/^\\d+(\\.\\d+)*$/.test('123')); console.log(/^\\d+(\\.\\d+)*$/.test('1.2.3.4')); // negative cases console.log(/^\\d+(\\.\\d+)*$/.test('1.')); console.log(/^\\d+(\\.\\d+)*$/.test('Jon Skeet')); 

RegExp('^(\\d+\\.)*(\\d+)$').test('1.2.3.4') 

is right. Thank you all.

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