简体   繁体   English

用于1或2或3十进制数字的正则表达式,不允许前导零,精度2和分数

[英]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. 精度2。

  4. Proper Fractions are allowed (0.__ numbers). 允许使用适当的分数(0 .__个数字)。

  5. No text before the decimal number 十进制数字前无文字

Regex should match the following: 正则表达式应符合以下条件:

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

The regex should not match the following: 正则表达式不应与以下内容匹配:

  • .45 0.45
  • 1234.45 1234.45
  • 023.45 023.45
  • 03.67 03.67
  • 845.7 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. 我不希望前导零,以防十进制数字有2或3位数字。 However, in case it`s proper fraction, I do want 0.__ to be allowed). 但是,如果它是适当的分数,我确实希望允许使用0 .__。

However, my regex does not match "0.__" decimal numbers because it expects the number to start with 1 due to " ^[1-9] ". 但是,我的正则表达式与十进制数字“ 0 .__”不匹配,因为由于“ ^[1-9] ”,它期望数字以1开头。

Please advise how can I modify my regex to match also "0.__" numbers. 请告知如何修改我的正则表达式以匹配“ 0 .__”数字。

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. (?!0+[1-9])是负向的前瞻,它将停止数字中的前导零。

Assuming you're using re.match, here's the shortest you can use: 假设您正在使用re.match,这是您可以使用的最短时间:

(?!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). 您不需要区别对待第一个数字,因此可以使用\\ d(与[0-9]相同),并确保第一个字符不是0,且负前瞻(?!0)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM