简体   繁体   中英

JavaScript regular expression check number only

I want a regular expression for the following values:

1) .1 = False.
2) 0.1 = True.
3) 1.1245 = True.
4) 1.2. = False.
5) 1.24.35 = False.
6) 21.152 = true.

This regex should check that the string represents an integer or is composed of only numbers and a single . representing a decimal point.

I am using: /^[\\+\\-]?\\d*\\.?\\d+(?:[Ee][\\+\\-]?\\d+)?$/ but it takes "1.2." as true .

You are taking the first digits set as none or more \\d* , you should use \\d+ , then it would work for the cases you want.

Can also look here

Edit: ^[\\+\\-]?\\d+(\\.?\\d+(?:[Ee][\\+\\-]?\\d+)?)?$

Your regex seems more complex than it needs to be. In order to live up to your requirements (starts with a number, ends with a number, at most one dot) you can use the following:

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

Edit: Or even simpler:

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

If you use the following regex

(?:\\d*.)?\\d+

It will match only real numbers.

If the input is like 1.2.3 it will return 1.2 .

Hope it helps!

你把点放在错误的地方,这应该工作

[\+\-]?[0-9]+(\.[0-9]+(?:[Ee][\+\-]?[0-9]+)?)?

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