为什么 Youtube URL ID Regex 在 Regex 服务中找到了 id 但在真正的 JS 代码中不起作用?

Why Youtube URL ID Regex find the id in the Regex service but doesn't work in the real JS code?

我创建了 YT Regexp 来匹配视频的 ID,它在 Regex 服务中工作 - regex101 但在实际代码中它无法以某种方式检测到 ID。在随附的屏幕截图中,您可以看到在服务中,匹配结果中存在一个 ID 组,但在控制台中却没有。

我想知道这怎么可能?也许我的正则表达式不正确或者它是某些正则表达式特定的行为?

我将不胜感激 help/info!

代码如下: 我的正则表达式

const YT_ID_REGEXP = /(?:https?:\/\/(?:www)?\.?y(?:2u\.be|outu\.be|outube.com)\/)(?:watch\?v=)?([\w\d]+)/gim;

It recognizes the standard YT link such as: 
  http://www.youtube.com/watch?v=Kmiw4FYTg2U  
and the shortcuts like: 
  http://youtu.be/ZRX8984sc 
or 
  http://y2u.be/w7ejDZ8SWv8

我准备了 playground & demo regex101 service demo

当您将 g 标志与 match 一起使用时,它不会 return 捕获的组。

尝试改用 exec。 如果您不想使用索引,可以使用命名组来方便。

var str = "some https://www.youtube.com/watch?v=cYXI344Siew YT link";

// adding ?<id> before the pattern of video id
var regx = /(?:https?:\/\/(?:www)?\.?y(?:2u\.be|outu\.be|outube.com)\/)(?:watch\?v=)?(?<id>[\w\d]+)/gmi

// Now to get the id directly
var {groups: { id }} = regx.exec(str);

console.log(id); 
//cYXI344Siew

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges#using_named_groups