我正在此页面上尝试此正则表达式:
http://www.regular-expressions.info/javascriptexample.html

其中Regex = (?:http:\/\/)?(?:www.)?facebook\.com\/([\w\-\.]*)?

和主题字符串= http://www.facebook.com/xxxxxx

这将返回两个匹配项:http://www.facebook.com/xxxxxxxxxxxx

我在chrome扩展程序中嵌入了相同的javascript,但是那里只显示了一个匹配项:'http://www.facebook.com/'。有任何想法吗 ?以下是代码:

var re = new RegExp("(?:http:\/\/)?(?:www.)?facebook\.com\/(?:profile\.php\?id=(?=\d.*))?([\w\-]*)?");
  var m = re.exec("http://www.facebook.com/xxxxx");
  if (m == null) {
    alert("No match");
  } else {
    var s = "Match at position " + m.index + ":\n";
    for (i = 0; i < m.length; i++) {
      s = s + m[i] + "\n";
    }
    alert(s);
  }

最佳答案

当regexp来自字符串时,每个反斜杠都应屏蔽:

var re = new RegExp("(?:http:\\/\\/)?(?:www.)?facebook\\.com\\/(?:profile\\.php\\?id=(?=\\d.*))?([\\w\\-]*)?");


在javascript中,您还可以创建不带字符串的regexp模式:

var re = /(?:http:\/\/)?(?:www.)?facebook\.com\/(?:profile\.php\?id=(?=\d.*))?([\w\-]*)?/;

关于javascript - 网页和Chrome扩展程序中不同的正则表达式行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6365429/

10-12 12:23
查看更多