首页 > 解决方案 > 正则表达式用于前面带有空格和 + 号的数字

问题描述

如果我只想接受数字,那么我将使用这个正则表达式

^[0-9]*$

但这里的问题是数字像

+1 00

没有被抓住,我的正则表达式会显示它是无效的

用户只需要输入数字,但中间只允许一个空格,并且开头的 + 号应该是可选的。

所以可以接受的是:

+1 11 1 1 11 
or
1 11 1 1 11 

不可接受的是:

+1    11 1 1 11
or
1 11     1 1 11 

请帮忙

标签: javascriptregex

解决方案


您可以尝试使用此正则表达式模式:

^\+?\d+(?:[ ]?\d+)*$

示例脚本:

console.log(/^\+?\d+(?:[ ]?\d+)*$/.test('+1 11 1 1 11')); // true

console.log(/^\+?\d+(?:[ ]?\d+)*$/.test('1 11 1 1 11'));  // true

console.log(/^\+?\d+(?:[ ]?\d+)*$/.test('+1    11 1 1 11')); // false

console.log(/^\+?\d+(?:[ ]?\d+)*$/.test('1 11    1 1 11'));  // false

这里使用的正则表达式模式说:

^                 from the start of the string
    \+?           match an optional leading +
    \d+           then match one or more digits
    (?:[ ]?\d+)*  followed by an optional single space and more digits,
                  zero or more times
$                 end of the string

推荐阅读