regex 使用匹配功能从存储的数据中提取电话号码

7vhp5slm  于 7个月前  发布在  其他
关注(0)|答案(3)|浏览(80)

我有下面的代码来匹配电话号码,并将它们存储在变量“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,所以任何东西都有帮助。

ne5o7dgx

ne5o7dgx1#

将正则表达式改为[0-9]{3}-[0-9]{3}-[0-9]{4}
你使用的{2,}表示2到无穷大之间的值,所以2002-01-23有两位数(23),因此与之匹配。
假设您的电话号码总是采用012-345-6789,那么[0-9]{3}-[0-9]{3}-[0-9]{4}应该适合您。

hec6srdp

hec6srdp2#

在这种情况下,您可以尝试/[0-9]{3}-[0-9]{3}-[0-9]{2,}/
PS:这不是一个javascript你在这里使用,但regex.这里是有用的网站尝试regexes了-https://regexr.com/

41zrol4v

41zrol4v3#

它需要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.

相关问题