1

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.

7
  • 1
    You should post what regex you have tried that did not work. Commented Nov 17, 2017 at 21:10
  • /^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/.test('1.2.') returns false, not true. Cannot reproduce what you are saying. Commented Nov 17, 2017 at 21:14
  • @trincot when I enter 1.2. in text box and print in console.log it shows true, but when I use 1.2.1 then it showing false. I want 1.2. should show false. Commented Nov 17, 2017 at 21:19
  • If you are open to other solutions and not restricted to just a regular expression, I'd suggest Number(x) === Number(x); when NaN, it will return false because NaN === NaN always returns false. Commented Nov 17, 2017 at 21:26
  • @RishatMuhametshin could you please demonstrate with any example. Commented Nov 17, 2017 at 21:28

4 Answers 4

2

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+)?)?$

Sign up to request clarification or add additional context in comments.

11 Comments

when I enter single digit then it display false.
Its unstable it is not working for other like "012.5.".
"012.5." should return false or?
Yes it is working fine in regex101.com/r/yXw3yB/1 but when I am using like below it return true for "1.2.". var reg = /^[\+\-]?\d+(\.?\d+(?:[Ee][\+\-]?\d+)?)?$/ console.log(reg.test((edValue.value)));
I want only one dot enter in the string. if you put second dot it should be false.
|
0

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!

Comments

0

you were puting the dot in the wrong place this should work

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

Comments

0

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+)?$

2 Comments

When I use "12.2." it returns true, if I changes with "12.2.3" then its working file. I want it should show false when I use "12.2.".
I can't reproduce that behavior. Are you sure that the error isn't in the surrounding code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.