【发布时间】:2011-11-16 07:39:46
【问题描述】:
我想知道正则表达式的样子:
- 只有整数
- 仅限小数点后两位以下的数字(23、23.3、23.43)
【问题讨论】:
标签: javascript regex
我想知道正则表达式的样子:
【问题讨论】:
标签: javascript regex
只有整数:
/^\d+$/
# explanation
\d match a digit
+ one or more times
最多有 2 位小数的数字:
/^\d+(?:\.\d{1,2})?$/
# explanation
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional
注意事项:
^ 和 $ 是字符串锚的开始和结束。如果没有这些,它将在字符串中的任何位置查找匹配项。所以/\d+/ 匹配'398501',但它也匹配'abc123'。锚点确保 整个 字符串与给定的模式匹配。\d 之前添加 -?。同样,? 表示“零次或一次”。var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/);
console.log(rx.test('abc')); // false
console.log(rx.test('309')); // true
console.log(rx.test('30.9')); // true
console.log(rx.test('30.85')); // true
console.log(rx.test('30.8573')); // false
【讨论】:
我。 [1-9][0-9]* 如果数字应该大于零(任何以非零数字开头的数字系列)。如果它应该是零或更多:(0|[1-9][0-9]*)(零或非零数)。如果它可以是负数:(0|-?[1-9][0-9]*)(零或可以在其前有一个减号的非零数字。)
二。像 I. 这样的正则表达式,后跟:(\.[0-9]{1,2})?,这意味着,可选的点后跟一位或两位数字。
【讨论】:
仅整数
/\d+/
一位或两位小数:
/\d(\.\d{1,2})?/
【讨论】: