简体   繁体   中英

Altering a regex float expression to enforce a leading number before decimal point

I have the following regex expression that validates via jquery a textbox element in html.

/^-?\d*[.]?\d*$/

I would like to alter this so that the decimal point can only be added if it has a leading number before it.

If someone could provide me the solution I'd be very grateful.

Just add + quantifier after first \d

^-?\d+[.]?\d*$

 const n1 = '.1'; const n2 = '0.1'; const n3 = '-0.1'; const regex = /^-?\d+[.]?\d*$/; console.log(`${n1} ==> ${regex.test(n1)}`); console.log(`${n2} ==> ${regex.test(n2)}`); console.log(`${n3} ==> ${regex.test(n3)}`);

Edit:

Above pattern will match strings that have no digits after the decimal such as "1." . If you want to enforce digits after decimal if decimal is present, use following regex

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

 const n1 = '1.'; const n2 = '1.1'; const regex = /^-?\d+(\.\d+)?$/; console.log(`${n1} ==> ${regex.test(n1)}`); console.log(`${n2} ==> ${regex.test(n2)}`);

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