regex 允许两个特定短语并继续

6qqygrtg  于 2023-10-22  发布在  其他
关注(0)|答案(3)|浏览(93)

我有一个RegEx,最初是这样的:

/https:\/\/medal.tv\/games\euro-truck-sim-2\/clips\/([A-z0-9-]+)(\/[A-z0-9]+)?(\??[A-z0-9]+\=?[A-z0-9]+-[A-z0-9]+)?/

这是完美的工作,但是,我希望它的工作都当它是“欧洲卡车SIM-2”和“进口剪辑”.我对RegEx没有太多的经验(实际上是零),我不知道我做错了什么。这就是我尝试过的,我不知道RegEx或其他东西是否与代码本身有关。

/https:\/\/medal.tv\/games\/(imported-clips|euro-truck-sim-2+)?\/clips\/([A-z0-9-]+)(\/[A-z0-9]+)?(\??[A-z0-9]+\=?[A-z0-9]+-[A-z0-9]+)?/

我看到的是,在导入剪辑匹配之后,在我的链接中没有其他内容:

https://medal.tv/clips/imported-clips

预期行为应为:

https://medal.tv/games/imported-clips/clips/remglmZK54/egmkr4t

https://medal.tv/games/euro-truck-sim-2/clips/remglmZK54/egmkr4t

换上

https://medal.tv/clips/remglmZK54
w7t8yxp5

w7t8yxp51#

这里有一个解决方案,用正则表达式匹配字符串的某些部分,并用String.prototype.replace()删除它们。

const str1 = 'https://medal.tv/games/imported-clips/clips/remglmZK54/egmkr4t';
const str2 = 'https://medal.tv/games/euro-truck-sim-2/clips/remglmZK54/egmkr4t';

let re =
  /(?<=https:\/\/medal.tv\/)games\/(imported-clips|euro-truck-sim-2)\/(?=clips\/[A-z0-9]+)|\/[A-z0-9]+$/g;

let out1 = str1.replace(re, '');
console.log(out1)

let out2 = str2.replace(re, '');
console.log(out2)

指纹

https://medal.tv/clips/remglmZK54
https://medal.tv/clips/remglmZK54

说明:
1.使用lookbehind(?<=)lookahead(?=)分别匹配前缀字符串https://medal.tv/和后缀字符串clips/remglmZK54。这是因为我们希望锚字符串的中间部分,并在最终结果中仍然保留前缀和后缀。

  1. games/imported-clips/games/euro-truck-sim-2的部分将被匹配并替换为空字符串'',因此使用games\/(imported-clips|euro-truck-sim-2)\/( ... | ... )表示逻辑OR
    1.我们还需要删除结尾的字母数字字符egmkr4t(不包括下划线_)以及最后的/,后者由\/[A-z0-9]+$和全局修饰符g处理。
z31licg0

z31licg02#

找到解决方案:

/https:\/\/medal.tv\/games\/(?:imported-clips|euro-truck-sim-2)\/clips\/([A-z0-9-]+)(\/[A-z0-9]+)?(\??[A-z0-9]+\=?[A-z0-9]+-[A-z0-9]+)?/

重新考虑A-z,因为这不会产生您期望的结果。
范围是代码点 * 0x 41 - 0x 7a *,包括 Za 之间的值。

    • 维基百科- ASCII -可打印字符 *

我建议使用 “大小写不敏感” 模式i,并将范围调整为a-z
此外,本发明还

  • 转义 *”medal.tv“*中的.
  • 0-9替换为\d
  • 并取消转义=
/https:\/\/medal\.tv\/games\/(?:imported-clips|euro-truck-sim-2)\/clips\/([a-z\d-]+)(\/[a-z\d]+)?(\??[a-z\d]+=?[a-z\d]+-[a-z\d]+)?/gi
var s = `https://medal.tv/games/imported-clips/clips/remglmZK54/egmkr4t
https://medal.tv/games/euro-truck-sim-2/clips/remglmZK54/egmkr4t`
var p = /https:\/\/medal\.tv\/games\/(?:imported-clips|euro-truck-sim-2)\/clips\/([a-z\d-]+)(\/[a-z\d]+)?(\??[a-z\d]+=?[a-z\d]+-[a-z\d]+)?/gi
console.log([...s.matchAll(p)])
iezvtpos

iezvtpos3#

找到解决方案:

/https:\/\/medal.tv\/games\/(?:imported-clips|euro-truck-sim-2)\/clips\/([A-z0-9-]+)(\/[A-z0-9]+)?(\??[A-z0-9]+\=?[A-z0-9]+-[A-z0-9]+)?/

相关问题