var cost_price = "15..00"
/*Cost price should be such that it should contain numbers and may not contain more than one dot*/
if(/^([0-9])|([.])/.test(cost_price)){
documet.write("Correct cost price");
}
现在尽管cost_price中有两个点我得到了问候消息。我应该在if条件下改变什么?
P.S。我结合了2 reg ex。一个检查数字是否正确,另一个检查点是否只出现一次。
答案 0 :(得分:4)
为什么不去
/^[0-9]+(\.[0-9]+)?$/
因此最后一部分完全可选? (?
指定" 匹配0到1次")
如果您想允许.15
,您可以将第一个[0-9]+
(匹配1到无穷大时间)更改为[0-9]*
(匹配0到无穷大时间)。
答案 1 :(得分:1)
正则表达式适用于您的情况:
/^\d+(\.\d+)?$/
答案 2 :(得分:0)
var cost_price = "15..00"
if (/\d+\.\d+/.test(cost_price)) {
documet.write("Correct cost price");
} else {
documet.write("Incorrect cost price");
}
http://regex101.com/r/cL8pP1
<强>说明强>
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “.” literally «\.»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»