2012-07-10 88 views
3

我发现这个正则表达式用于验证浮点数。但我不知道2-1会如何接受。以下评估为真。我不能使用parseFloat,因为我需要能够接受“,”而不是“。”。也。我写了re2,同样的结果。浮点数的正则表达式

var re1 = new RegExp("^[-+]?[0-9]*\.?[0-9]+$"); 
console.log(re1.test("2-1")); 

var re2 = new RegExp("^([0-9]+)\.([0-9]+)$"); 
console.log(re2.test("2-1")); 

回答

3

如果您使用构造函数生成的正则表达式,你必须转义反斜线,即\成为\\

var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$"); 

另一种选择是使用文字语法不需要ES caping:

var re1 = /^[-+]?[0-9]*\.?[0-9]+$/ 
+0

谢谢你 – pethel 2012-07-10 08:00:14

0

如何用句点(“。”)替换逗号(“,”)然后使用parseFloat?

+0

这可以工作。但我仍然对以上:) – pethel 2012-07-10 07:45:51

3

有时当你创建一个正则表达式字符串时,你甚至不得不转义反斜杠;这当然可以用一个反斜杠来完成,所以最终的正则表达式看起来像"\\.*"

这样做,我能得到正确的结果,因为看到here

var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$"); 
console.log(re1.test("2-1")); 

var re2 = new RegExp("^([0-9]+)\\.([0-9]+)$"); 
console.log(re2.test("2-1")); 

console.log(re1.test("2.1")); 
console.log(re2.test("2.1"));​