为什么此正则表达式执行不返回匹配项

发布于 2025-01-10 13:09:51 字数 1095 浏览 2 评论 0原文

我的正则表达式是:

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)。

regexr 行为

然而,当我在 Google Chrome 的控制台中尝试相同的代码时,代码返回 null:

google chrome console

为什么它没有显示在 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).

regexr behaviour

Yet, when I try the same code in Google Chrome's console, the code returns null:

google chrome console

Why doesn't it show up in the chrome console?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泼猴你往哪里跑 2025-01-17 13:09:51

由于您是从字符串创建正则表达式,因此必须转义反斜杠。

let a = new RegExp("(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\\.com\/(?<profile>(?![A-z]+\\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\\w.\\-]+)\\/?", "g")
console.log(a.exec("https://facebook.com/peterparker"))

内联创建它不会有这个问题。

let a = /(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\.com\/(?<profile>(?![A-z]+\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\w.\-]+)\/?/g
console.log(a.exec("https://facebook.com/peterparker"))

Since you're creating your regex from a string, you have to escape your backslashes.

let a = new RegExp("(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\\.com\/(?<profile>(?![A-z]+\\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\\w.\\-]+)\\/?", "g")
console.log(a.exec("https://facebook.com/peterparker"))

Creating it inline does not have this problem.

let a = /(?:https?:)?\/\/(?:www\.)?(?:facebook|fb)\.com\/(?<profile>(?![A-z]+\.php)(?!marketplace|gaming|watch|me|messages|help|search|groups)[\w.\-]+)\/?/g
console.log(a.exec("https://facebook.com/peterparker"))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文