javascript - 正则表达式用于前面带有空格和 + 号的数字
问题描述
如果我只想接受数字,那么我将使用这个正则表达式
^[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
请帮忙
解决方案
您可以尝试使用此正则表达式模式:
^\+?\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
推荐阅读
- search - 在 Sitefinity 后端动态模块搜索中搜索标题以外的字段
- c# - NSwag 变更控制器说明
- gatsby - 生产 Gatsby 博客未在 MDX 文件中呈现 TailwindCSS 类
- javascript - 如何从两个/三个文件中获取差异并将它们组合到节点中?
- python - Pandas:使用混合数据类型对多级列进行排序
- javascript - 使用 != 和 not-in 查询会在 firestore 中使用 Query.where 引发错误
- php - 执行使用 reffrer url 打开的文件
- ruby - 如何显示所有最新或待处理的 rake taks?
- jolt - 需要 JOLT 规范将源 JSON 格式转换为所需的 JSON 格式
- mapbox - 根据数据字段对 mapbox studio poi 图标进行排序