简体   繁体   中英

Regex for 1 or 2 or 3 decimal number, no leading zeros, precision 2 and fractions are allowed

I am trying to create a regex which meets the following:

  1. One or two or three decimal number.

  2. No leading zeros inside the decimal number.

  3. Precision 2.

  4. Proper Fractions are allowed (0.__ numbers).

  5. No text before the decimal number

Regex should match the following:

  • 123.45
  • 103.67
  • 100.45
  • 25.68
  • 5.97
  • 1.05
  • 23.07
  • 187.08
  • 0.26

The regex should not match the following:

  • .45
  • 1234.45
  • 023.45
  • 03.67
  • 845.7

I came up with the following regex:

(?<!.)^([1-9][0-9]{0,2}\.[0-9][0-9])$

It meets all of the above except fractions.

I don't want leading zeros in case the decimal number has 2 or 3 digits. However, in case it`s proper fraction, I do want 0.__ to be allowed).

However, my regex does not match "0.__" decimal numbers because it expects the number to start with 1 due to " ^[1-9] ".

Please advise how can I modify my regex to match also "0.__" numbers.

Try this regex.

\b(?!0\d{1,2}\.)\d{1,3}\.\d{2}\b

See Demo

What about this:

\b(0|[1-9]\d{0,2})\.\d{2}\b

Here you can see that it matches exactly what you want.

You can use this regex:

^(?!0+[1-9])\d{1,3}\.\d{2}$

RegEx Demo

(?!0+[1-9]) is a negative lookahead that will stop leading zeroes in the number.

Assuming you're using re.match, here's the shortest you can use:

(?!0)\d{1,3}\.\d{2}

If you are using search:

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

You don't need to treat the first number differently, so you can use \\d (which is the same as [0-9]) and make sure the first character is not 0 with a negative lookahead (?!0).

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