JavaScript负面观察 [英] JavaScript Negative Lookbehind

查看:63
本文介绍了JavaScript负面观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了许多其他问题围绕JavaScript的负面观察,但我似乎无法模仿它们。我有以下正则表达式:

I've looked through numerous other questions up here surrounding a negative lookbehind for JavaScript but I can't seem to mimic them. I have the following Regex:

\b((?:http[s])?\S+\.\S+\.(?:\S+\.?){1,4})(?<!@)\b` 

此正则表达式的基础是它匹配以下网址:

and the basis of this Regex is it matches web addresses like:


  • www.msn.com

  • http://www.msn.com

  • https://www.google.com

  • http://msdn.microsoft.com

  • www.msn.com
  • or http://www.msn.com
  • or https://www.google.com
  • or http://msdn.microsoft.com.

但是,它也匹配 name@d1.d2.d3.d4 因为 @ 符号后的众多域名。我需要为 @ 标志执行负面的后视。

However, it also matches name@d1.d2.d3.d4 because of the numerous domain names following the @ sign. I need to perform a negative lookbehind for that @ sign.

希望有人可以帮我一把!

Hopefully somebody can give me a hand!

UPDATE

更新以包含我用来创建的替换字符串匹配文本中的超链接。

Updating to include the replacement string that I'm using to create the hyperlink out of the matched text.

replace(webLinkPattern, "<a href=\"http://$2\" target=\"_blank\" onclick=\"preventDualEditing(event)\">$2</a>");

更新2 - 答案

ts = ts.replace(webLinkPattern, function (url) {
    if (url.indexOf('@') != -1) {
        return url;
    }

    return url.replace(webLinkPattern, "<a href=\"http://$&\" target=\"_blank\" onclick=\"preventDualEditing(event)\">$&</a>");
});


推荐答案

JavaScript不支持lookbehind断言,所以你'我必须在你自己的代码中处理这个问题。一个选项只是在结果中包含 @ ,然后在 @ 存在时丢弃匹配:

JavaScript doesn't support lookbehind assertions, so you'll have to handle this in your own code. One option is simply to include the @ in the result, and then discard the match if the @ is there:

replace(/(?:\b|@)(?:https?)?\S+\.\S+\.(?:\S+\.?){1,4}\b/,
        function(url) {
          if(url.indexOf('@') > -1)
            return url;
          return '<a href="' + url + ' target="_blank"' +
                 ' onclick="preventDualEditing(event)">' + url + '</a>';
        }
       );

或者,您可以在回调中检查前面的 @ ,即使没有将其包含在 url 中:

Alternatively, you can check for a preceding @ in the callback, even without including it in url:

replace(/\b(?:https?)?\S+\.\S+\.(?:\S+\.?){1,4}\b/,
        function(url, pos, str) {
          if(pos > 0 && str.charAt(pos - 1) == '@')
            return url;
          return '<a href="' + url + ' target="_blank"' +
                 ' onclick="preventDualEditing(event)">' + url + '</a>';
        }
       );

(请注意,我还更改了 http [s] https?,这就是你的意思。 http [s] 与<$相同c $ c> https ,因为 [s] 是一个匹配任何 s 。)

(Note that I've also changed http[s] to https?, which is what you meant. http[s] is the same as https, since [s] is a character class matching any character that's s.)

这篇关于JavaScript负面观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆