Home > Enterprise >  How can I limit the decimal point in a regex?
How can I limit the decimal point in a regex?

Time:06-22

When a decimal point is not allowed at the beginning or end, it can be in the middle and there must be only one decimal point.

I used regular expressions to create the expression I wanted. Numbers must be entered, but no English characters or other string values ​​can be used. Only one decimal point can be used, but I do not want to allow a decimal point at the beginning. But the last one is allowed to be inserted. One decimal point in the middle of a number with a trailing decimal point is allowed. In addition, even if there is no decimal point in the middle of a number, it is allowed to have a decimal point at the end. like this

(o )13.4. 13.
(x) .

However, when using my regular expression, the decimal point is used more than once, and the decimal point is also used at the beginning and end.

this is my regex

let regex = /[^\d.]/g;

how can i fix this?

CodePudding user response:

const str = '123.12';

const regex = new RegExp('^\\d ([.]\\d )?$');

console.log(regex.test(str));

CodePudding user response:

in my. you might find a way to fix your problem ,but regex sometimes is not the best solution. if possible ,just write a method to limit , 1.only numbers or point are allowed 2.point is only one time in the string, but not begin or the end

it's might not hard for you, and trust me it would be fast.

CodePudding user response:

I just added the answer that includes the negative form.

str = '13.4';

const regex2 = new RegExp('^\-?\[0-9] ([.]\[0-9] )?$');


console.log(regex2.test(str));
str = '-13.4';
console.log(regex2.test(str));
str = '-13';
console.log(regex2.test(str));
str = '-1d3';
console.log(regex2.test(str));

  • Related