Twitch夹正则表达式

问题描述

我当时在看这个post,但是twitch最近将其剪辑的网址更改为其他格式。

新格式为:

https://www.twitch.tv/loserfruit/clip/HungryBillowingSandpiperTebowing

剪辑的ID为HungryBillowingSandpiperTebowing

如何使用正则表达式提取ID?

我最好的尝试是使用替换方法,这样的方法能够涵盖所有方面吗?

  var Y = "/clip/";
  var X = twitchurl;
  var Z = X.replace(new RegExp(".*" + Y),"");

任何帮助将不胜感激。

解决方法

您尝试在您的Y/clip/字符串)之前尽可能地匹配除换行符以外的任何零个或多个字符。

相反,您应该使用/,在Y部分的之后,尽可能匹配[^/]+以外的任何一个或多个字符。

您可以使用基于向后搜索的解决方案或一个捕获组:

const Y = "/clip/";
const twitchurl = "https://www.twitch.tv/loserfruit/clip/HungryBillowingSandpiperTebowing";
// Using a capturing group
const result = twitchurl.match(new RegExp(`${Y}([^/]+)`))?.[1];
console.log(result);
// Using a lookbehind
const result2 = twitchurl.match(new RegExp(`(?<=${Y})[^/]+`))?.[0];
console.log(result2);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...