^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]+\.[0-9]*[1-9][0-9]*)$
Run Code Online (Sandbox Code Playgroud)
我不太了解正则表达.上面的正则表达式不允许输入.2.但它允许所有其他小数,如0.2,0.02等.我需要让这个表达式允许数字如.2,.06等.....
Joe*_*oey 10
只需将+after 更改[0]为ansterisk`*":
^([0-9]*[1-9][0-9]*(\.[0-9]+)?|[0]*\.[0-9]*[1-9][0-9]*)$
Run Code Online (Sandbox Code Playgroud)
因此,不要在点之前允许一个或多个零,只允许0或更多.
我喜欢这个浮点数的正则表达式,它非常聪明,因为它不匹配0.0数字.它要求在期间的任何一侧至少有一个非零数字.想想我会把它分解成它的部分,以便更深入地理解它.
^ #Match at start of string
( #start capture group
[0-9]* # 0-9, zero or more times
[1-9] # 1-9
[0-9]* # 0-9, zero or more times
( #start capture group
\. # literal .
[0-9]+ # 0-9, one or more times
)? #end group - make it optional
| #OR - If the first option didn't match, try alternate
[0]+ # 0, one or more times ( change this to 0* for zero or more times )
\. # literal .
[0-9]* # 0-9, zero or more times
[1-9] # 1-9
[0-9]* # 0-9, zero or more times
) #end capture group
$ #match end of string
Run Code Online (Sandbox Code Playgroud)
正则表达式内部有两个较小的模式,第一个匹配数字> = 1(具有至少一个非零字符的情况)的情况.可选地允许具有一个或多个尾随数字的句点.第二个匹配<1.0并确保点的右侧至少有一个非零数字.
约翰内斯的回答已经为您[0]*提供了问题的解决方案.
正则表达式的快捷方式的夫妇,你可以更换的任何实例[0-9]与\d大多数正则表达式的口味.也[0]只是匹配0所以你也可以使用0*而不是[0]*.最终的正则表达式:
/^(\d*[1-9]\d*(\.\d+)?|0*\.\d*[1-9]\d*)$/
Run Code Online (Sandbox Code Playgroud)