Javascript 正则表达式只允许整数和小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12475704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:03:13  来源:igfitidea点击:

regular expression to allow only integer and decimal

javascriptregex

提问by subash

Possible Duplicate:
Simple regular expression for a decimal with a precision of 2?

可能的重复:
精度为 2 的小数的简单正则表达式?

i want to know regular expression that would allow only integers and decimal numbers of any length starting from 0 to infinity in javascript. can any one help me in getting that done

我想知道在javascript中只允许从0到无穷大的任何长度的整数和十进制数的正则表达式。任何人都可以帮助我完成这项工作吗

回答by Florian F.

This code would do :

这段代码会做:

var str = "1.2"
var regexp = /^[0-9]+([,.][0-9]+)?$/g;
var result = regexp.test(str);
?alert(result);?

Where:

在哪里:

  • str is the string you want to test
  • regexp is what you're testing the string with (built like: /pattern/modifiers)
  • result is a boolean, true if it matches, false otherwise
  • str 是您要测试的字符串
  • 正则表达式是什么,你正在测试用字符串(建这样的:/pattern/modifiers
  • 结果是一个布尔值,如果匹配则为真,否则为假

You should check this link about the RegExp object in JavaScript: http://www.w3schools.com/jsref/jsref_obj_regexp.asp

您应该检查有关 JavaScript 中 RegExp 对象的链接:http: //www.w3schools.com/jsref/jsref_obj_regexp.asp

About the regexp itself :

关于正则表达式本身:

  • ^: start of the string
  • [0-9]+: at least one digit
  • [,.]: dot or comma
  • [0-9]+: same as above
  • (xxxxx)?: the expression inside the parenthesis can be present or not
  • $: end of the expression
  • ^: 字符串的开始
  • [0-9]+: 至少一位
  • [,.]: 点或逗号
  • [0-9]+: 同上
  • (xxxxx)?: 括号内的表达式可以存在也可以不存在
  • $: 表达式结束

You should also check Wikipedia page for regexp if you'd like to learn more, it's rather well done.

如果您想了解更多信息,您还应该查看 Wikipedia 页面的 regexp,它做得相当好。

回答by Ram G Athreya

Try this

尝试这个

^[\d.]+$


^- start of line

^- 行首

[]- array of selections

[]- 一系列选择

\d- any digit

\d- 任何数字

.- dot character

.- 点字符

+- 1 or many

+- 1 个或多个

$- end of line

$- 行结束