使用匹配功能从存储的数据中挑选电话号码

using match function to pick out phone numbers from stored data

提问人:Peterson Rainey 提问时间:10/26/2023 最后编辑:Mark SchultheissPeterson Rainey 更新时间:10/26/2023 访问量:40

问:

我有以下代码来匹配电话号码并将它们存储在变量“phone”中。但是,它也会将日期与电话号码匹配。例如,如果我给它以下字符串:以下匹配函数同时保存 & 。我将如何调整代码,使其仅保存数字?html.Code = 'call us at 517-156-4435 on the date 2002-01-23''517-156-4435''2002-01-23''517-156-4435'

phone = htmlCode.match(/[0-9]+-[0-9]+-[0-9]{2,}/)[0];

我不知道要采取什么其他步骤来解决这个问题,我刚刚开始学习javascript,所以任何事情都有帮助。

JavaScript 正则表达式 匹配

评论

0赞 Diego D 10/26/2023
你对正则表达式有什么了解吗?u 在那里用 {2,} 使用了一个非常复杂的量词,所以我想你明白为什么 + 会匹配任何高于零的数字

答:

2赞 Kousha 10/26/2023 #1

将正则表达式更改为[0-9]{3}-[0-9]{3}-[0-9]{4}

您使用的是介于 2 和无穷大之间的平均值。所以有两个数字 (23),因此匹配它。{2,}2002-01-23

假设您的电话号码始终采用 的格式,那么应该适合您。012-345-6789[0-9]{3}-[0-9]{3}-[0-9]{4}

0赞 Senyaak 10/26/2023 #2

在您的情况下,您可以尝试 ./[0-9]{3}-[0-9]{3}-[0-9]{2,}/

PS:这不是你在这里用的,但是.这是一个有用的网站来尝试正则表达式 - https://regexr.com/javascriptregex

0赞 smpa01 10/26/2023 #3

它需要 的模式匹配 。3 numerical values followed by - followed by 3 numerical values followed by - followed by 4 numerical values

const paragraph = 'call us at 517-156-4435 on the date 2002-01-23';
  const regex = /\d{3}-\d{3}-\d{4}/g
  const found = paragraph.match(regex)[0];
  
  console.log(found);

  \d{3} Matches exactly three digits.
  - Matches a hyphen.
  \d{3} Matches exactly three digits.
  - Matches another hyphen.
  \d{4} Matches exactly four digits.