首页 > 解决方案 > 正则表达式允许以下符号

问题描述

我正在尝试进行简单的电话号码验证,并且为此进行了正则表达式验证。我想允许用户输入以下内容:

  1. 任何数字
  2. -
  3. +
  4. (
  5. )
  6. space/空白

目前我有这样的东西:/[0-9-+()\s]*/im,但它似乎不起作用。有人可以帮我吗?我没有针对任何特定国家/地区,因此我不想遵循任何严格的格式。

标签: javascriptregex

解决方案


您需要从^字符开始强制它从头开始匹配,并从$字符强制它匹配到最后。否则它将匹配它可以匹配的内容并忽略除此之外不匹配的任何内容。你也可以对它更有指导性。例如,一个+字符可能只允许作为第一个字符,或者您可能希望强制至少有 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}`)


推荐阅读