简体   繁体   English

JavaScript正则表达式匹配电话号码,但不匹配HTML属性

[英]JavaScript Regex to Match Phone numbers but not in HTML attributes

We're needing a match phone numbers in some chunks of HTML with JavaScript and are very close but are having problems. 我们需要使用JavaScript在HTML的某些部分中匹配电话号码,并且该电话号码非常接近,但存在问题。 We don't want to match phone numbers that show up in attributes such as max-length="404-555-1212" . 我们不想匹配显示在诸如max-length="404-555-1212"属性中的电话号码。 Consider the following text: 考虑以下文本:

Sample:

Shouldn’t Match:
max-length='0123456789'
max-length="0123456789"
max-length=012-345-6789"

Don’t want the >
<strong>866.643.4170</strong>

Don’t really want this plus included either:
+1-(800)-555-2468

abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789 +-.,!@#$%^&*();\/|<>"'
12345 -98.7 3.141 .6180 9,000 +42
555.123.4567     +1-(800)-555-2468

With the following Regex, we are able to grab all of the phone numbers but it does not exclude the attributes: 使用以下正则表达式,我们可以获取所有电话号码,但不排除属性:

/(\d{1}[-. ])?\(?\d{3}\)?[-. ]? *\d{3}-? *[-. ]?\d{4}/g

We tried the following but it is leaving the > at the end of <strong> : 我们试过以下,但它留下>在结束<strong>

/[^"='](\d{1}[-. ])?\(?\d{3}\)?[-. ]? *\d{3}-? *[-. ]?\d{4}/g

Any thoughts on how to make this work? 对如何进行这项工作有任何想法吗?

So someone answered this question yesterday and I was coming back to accept the answer but it had been removed. 所以昨天有人回答了这个问题,我回来接受答案,但是答案已被删除。 However, the solution that they provided did work so, for posterity, I wanted to post the solution that they had given. 但是,他们提供的解决方案确实起作用,因此,为后代,我想发布他们提供的解决方案。

Here is the regex that solves the problem: 这是解决问题的正则表达式:

/(?:\d[-. ])?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}(?!["'])/g

And here is a link to the working example: 这是工作示例的链接:

http://regex101.com/r/rK6wY1/1 http://regex101.com/r/rK6wY1/1

I wish I could have given credit to the original answerer. 我希望我能相信最初的回答者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM