gpt4 book ai didi

javascript - 如何在 JavaScript 中使用 RegEx 从 twitch 剪辑中提取 URL

转载 作者:行者123 更新时间:2023-11-28 17:20:15 25 4
gpt4 key购买 nike

所以我不擅长正则表达式,我需要从字符串中提取链接。

示例:

str = 'hi check this https://clips.twitch.tv/KindYummyCarrotPeteZaroll clip!!'

我需要从字符串中提取完整的 URL“https://clips.twitch.tv/KindYummyCarrotPeteZaroll”。

剪辑的 ID 是“KindYummyCarrotPeteZaroll”,每个 URL 中的 ID 都不同。

str 可以有多个以不同方式处理的链接。我们必须匹配https://clips.twitch.tv/ID .

最佳答案

尝试以下代码:

var paragraph = 'hi check this https://clips.twitch.tv/KindYummyCarrotPeteZaroll clip!!';
var regex = /(?:https:\/\/)?clips\.twitch\.tv\/(\S+)/i;
var result = paragraph.match(regex);
console.log(result);
console.log('Clip ID: ' + result[1]);

剪辑的 ID 将位于 result[1] 中。

说明:

  • (?:https:\/\/)?clips\.twitch\.tv\/ 与确切的字符串 https://clips.twitch.tv/ 匹配> 或 clips.twitch.tv/,括号后面的问号表示括号内的文本出现 0 或 1 次,?: 表示我们不希望为了捕获它,反斜杠只是为了转义特殊字符
  • (\S+) - \S 匹配任何非空白字符,+ 表示出现一次或多次,括号存在,因此匹配的文本在单独的字段中返回
  • 由于常规字符串括在(双)引号中,因此正则表达式括在斜杠中
  • 结束斜杠后面可能有各种修饰符,在我们的例子中是 /i 表示不区分大小写的匹配

有关正则表达式的更多详细信息,请参阅 documentation on MDN .

关于javascript - 如何在 JavaScript 中使用 RegEx 从 twitch 剪辑中提取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52633162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com