首页 > 解决方案 > 正则表达式检查第一个字符为 + 和其他只是数字

问题描述

我的用例是验证字符串仅包含 + 和数字。我尝试了很多正则表达式,但无法解决我的问题。

我使用/^[0-9]+$/了正则表达式,但在第 2 次和第 3 次(显然是因为它有一个字符)输入失败了。

我的需要是,

if the input is 00000094777216903 - TRUE
if the input is +947777216903     - TRUE (+ is fine if it is in the beginning of the string)
if the input is +947777216903A    - FALSE
if the input is 0000777216903A    - FALSE

任何人都可以帮助我实现我在 JS 中的需求。

标签: javascriptregex

解决方案


试试这个正则表达式 https://regex101.com/r/6wW84L/2

/(\+){0,1}[0-9]+$/

您在下面有一个工作示例 This /(+){0,1}[0-9]+$/ not //(+){0,1}[0-9]+$//

在此处输入图像描述


推荐阅读