简体   繁体   中英

javascript regex trailing zeros

Javascript regex

I have following regex, i want to un-match zeros after decimal, 1.0 or 1.00 should not match but should match 1.25 or 1.2

^(?!0\.)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d{1,2})?$

it accepts following inputs

1.00
1.25
does not accept leading zero ex. 0.25
100
1000
1,000
100,000

You need to add a negative lookahead at the end:

^(?!0\.)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.(?!0+$)\d{1,2})?$
                                       ^^^^^^^

See the regex demo

The (?!0+$) negative lookahead restricts the subsequent consuming subpattern \\d{1,2})?$ so that the \\d{1,2} cannot match 00 or 0 any longer.

这是从相反的角度看待它是允许的,而不是排除的:

^[1-9],?[0-9]*.?[1-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