请有人请说明这个正则表达式......看起来很难理解......
/^[0-9]{1,}((\.){1}[0-9]{1,}){0,1}$/.test(value)
值是我从文本框发送的内容以验证...
答案 0 :(得分:4)
^ // start with
[0-9]{1,} // one or more of 0-9
(
(\.){1} // a period
[0-9]{1,} // one or more of 0-9
){0,1} // zero or one of this group
$ // until end
甚至更短:
^[0-9]+((\.)[0-9]+)?$
即。一系列数字,可选地后跟一个句号字符和一系列数字。
所以像
一样0011221100
12345
1.23456
0.0
0000.1111
将匹配。
答案 1 :(得分:1)
编辑:操作不同,所以我更新了解释。
简单地说:
"
^ # Assert position at the beginning of the string
[0-9] # Match a single character in the range between “0” and “9”
{1,} # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 1
( # Match the regular expression below and capture its match into backreference number 2
\. # Match the character “.” literally
){1} # Exactly 1 times
[0-9] # Match a single character in the range between “0” and “9”
{1,} # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
){0,1} # Between zero and one times, as many times as possible, giving back as needed (greedy)
\$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
"
编辑2:
你可能想要写这样的正则表达式:
^\d+((\.)+\d+)?$
完全与原始版本具有相同的含义,它当然更具可读性和紧凑性。
编辑3:
要考虑之前的可选整数部分。只需将量词从{1,}更改为{0,},即从+到*:
^\d*((\.)+\d+)?$