javascript - 正则表达式允许以下符号
问题描述
我正在尝试进行简单的电话号码验证,并且为此进行了正则表达式验证。我想允许用户输入以下内容:
- 任何数字
- -
- +
- (
- )
space
/空白
目前我有这样的东西:/[0-9-+()\s]*/im
,但它似乎不起作用。有人可以帮我吗?我没有针对任何特定国家/地区,因此我不想遵循任何严格的格式。
解决方案
您需要从^
字符开始强制它从头开始匹配,并从$
字符强制它匹配到最后。否则它将匹配它可以匹配的内容并忽略除此之外不匹配的任何内容。你也可以对它更有指导性。例如,一个+
字符可能只允许作为第一个字符,或者您可能希望强制至少有 7 个字符。下面的示例代码显示了其中的一些。
// r1 fixes the one you were trying by adding ^ and $
const r1 = /^[-+0-9()\s]*$/
// = =
// r2 adds rules like a "+" can only appear at the start
// and there must be at least 7 digits
const r2 = /^\+?[-0-9()\s]{7,}$/
// === ====
const tests = [
"123 456-7890",
"789",
"+4 9084342",
"hello",
"123+457+432",
"1234567!"
]
for (const num of tests) console.log(`r1: ${r1.test(num)} - ${num}`)
console.log("-----")
for (const num of tests) console.log(`r2: ${r2.test(num)} - ${num}`)
推荐阅读
- c# - 无法在 Visual Studio 的 Visual Basic.net 中创建 Windows 窗体应用程序
- unity3d - Unity 2019 - 着色器图 - 如何在 UIImage 中重新创建填充功能
- objective-c - 尝试将 Object-C 转换为 Applescriptobjc 以用于 instagram 帖子查找器
- java - 写入 txt 文件,空指针异常
- python - 如何使用 Apache2、mod_wsgi 和 Anaconda 运行 Django 应用程序?
- c - 如果使用两个结构,如何存储二叉搜索树的根?
- spring-boot - 如何在春季靴子中暴露骆驼mbean?
- java - 我无法按照 udacity 的教程生成 SHA1 密钥
- javascript - 如何通过 Javascript 从 JSON 输入创建 HTML?
- python - 从 ABC 到 AABBCC 的 python 列表转换