javascript - 使用正则表达式在不在 anchor 中的页面上查找电话号码

标签 javascript regex negative-lookahead

我有这个用于搜索电话号码模式的正则表达式:

[(]?\d{3}[)]?[(\s)?.-]\d{3}[\s.-]\d{4}

这与以下格式的电话号码匹配:

123 456 7890
(123)456 7890
(123) 456 7890
(123)456-7890
(123) 456-7890
123.456.7890
123-456-7890

我想扫描整个页面(使用 JavaScript)以查找此匹配项,但排除已存在于 anchor 内的此匹配项。 找到匹配项后,我想将电话号码转换为移动设备的点击通话链接:

(123) 456-7890 --> <a href="tel:1234567890">(123) 456-7890</a>

我很确定我需要进行否定查找。我已经试过了,但这似乎不是正确的想法:

(?!.*(\<a href.*?\>))[(]?\d{3}[)]?[(\s)?.-]\d{3}[\s.-]\d{4}

最佳答案

Don't use regular expressions to parse HTML .使用 HTML/DOM 解析器获取文本节点(浏览器可以为您过滤它,例如删除 anchor 标记和所有太短而无法包含电话号码的文本),您可以直接检查文本。

例如,使用 XPath(有点难看,但支持以大多数其他 DOM 方法不支持的方式直接处理文本节点):

// This query finds all text nodes with at least 12 non-whitespace characters
// who are not direct children of an anchor tag
// Letting XPath apply basic filters dramatically reduces the number of elements
// you need to process (there are tons of short and/or pure whitespace text nodes
// in most DOMs)
var xpr = document.evaluate('descendant-or-self::text()[not(parent::A) and string-length(normalize-space(self::text())) >= 12]',
                            document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0, len=xpr.snapshotLength; i < len; ++i) {
    var txt = xpr.snapshotItem(i);
    // Splits with grouping to preserve the text split on
    var numbers = txt.data.split(/([(]?\d{3}[)]?[(\s)?.-]\d{3}[\s.-]\d{4})/);
    // split will return at least three items on a hit, prefix, split match, and suffix
    if (numbers.length >= 3) {
        var parent = txt.parentNode; // Save parent before replacing child
        // Insert new elements before existing element; first element is just
        // text before first phone number
        parent.insertBefore(document.createTextNode(numbers[0]), txt);

        // Now explicitly create pairs of anchors and following text nodes
        for (var j = 1; j < numbers.length; j += 2) {
            // Operate in pairs; odd index is phone number, even is
            // text following that phone number
            var anc = document.createElement('a');
            anc.href = 'tel:' + numbers[j].replace(/\D+/g, '');
            anc.textContent = numbers[j];
            parent.insertBefore(anc, txt);
            parent.insertBefore(document.createTextNode(numbers[j+1]), txt);
        }
        // Remove original text node now that we've inserted all the
        // replacement elements and don't need it for positioning anymore
        parent.removeChild(txt);

        parent.normalize(); // Normalize whitespace after rebuilding
    }
}

郑重声明,基本过滤器在大多数页面上都有帮助很多。例如,在这个页面上,现在,正如我所看到的(将因用户、浏览器、浏览器扩展和脚本等而异)没有过滤器,查询的快照 'descendant-or-self::text()' 将有 1794 个项目。省略以 anchor 标记为父的文本,'descendant-or-self::text()[not(parent::A)]' 将其降低到 1538,以及完整的查询,验证非- 空白内容至少有 12 个字符长,可以减少到 87 个项目。将正则表达式应用于 87 个项目是性能方面的小改动,并且您已经消除了使用不合适的工具解析 HTML 的需要。

关于javascript - 使用正则表达式在不在 anchor 中的页面上查找电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322418/

相关文章:

c# - 在任何第一个数字之前拆分字符串

regex - 有没有办法在 vim 正则表达式中进行负前瞻?

javascript - Redux-Form 中的可编辑组合框

javascript - 按名称附加对象元素 javascript

javascript - 解构值并将其重命名为字符串键

regex - 如何使用正则表达式负前瞻

regex - 正则表达式 - 负前瞻

javascript - 提交时确认表格

regex - Perl,如何确定变量值是否为数字?

用于解析字符串的 PHP Regex 帮助