为什么此正则表达式执行不返回匹配项
我的正则表达式是:
let a = new RegExp("(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\.com\/(?<profile>(?![A-z]+\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\w.\-]+)\/?", "g")
它基本上是此处所见的修改facebook 从 facebook url 中提取用户名。
我的测试字符串是 https://facebook.com/peterparker
,我的代码是:
a.exec("https://facebook.com/peterparker")
当我在 RegExr,它工作正常。它显示了捕获的正确组 (peterparker
)。
然而,当我在 Google Chrome 的控制台中尝试相同的代码时,代码返回 null:
为什么它没有显示在 Chrome 控制台中?
My regex is:
let a = new RegExp("(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\.com\/(?<profile>(?![A-z]+\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\w.\-]+)\/?", "g")
It's basically a modification of the one seen here for facebook to extract the username from a facebook url.
My test string is https://facebook.com/peterparker
and my code is:
a.exec("https://facebook.com/peterparker")
When I try this in RegExr, it works fine. It shows the correct group captured (peterparker
).
Yet, when I try the same code in Google Chrome's console, the code returns null:
Why doesn't it show up in the chrome console?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您是从字符串创建正则表达式,因此必须转义反斜杠。
内联创建它不会有这个问题。
Since you're creating your regex from a string, you have to escape your backslashes.
Creating it inline does not have this problem.