[英]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: 我正在尝试创建一个满足以下条件的正则表达式:
One or two or three decimal number. 一或两个或三个十进制数。
No leading zeros inside the decimal number. 十进制数字内没有前导零。
Precision 2. 精度2。
Proper Fractions are allowed (0.__ numbers). 允许使用适当的分数(0 .__个数字)。
No text before the decimal number 十进制数字前无文字
Regex should match the following: 正则表达式应符合以下条件:
The regex should not match the following: 正则表达式不应与以下内容匹配:
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 .__”数字。
You can use this regex: 您可以使用此正则表达式:
^(?!0+[1-9])\d{1,3}\.\d{2}$
(?!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.