gpt4 book ai didi

javascript - 如何使用正则表达式 javascript 获取最后一次出现的情况?

转载 作者:行者123 更新时间:2023-12-03 00:32:36 25 4
gpt4 key购买 nike

你能帮我从字符串中提取“women-watches”吗:

https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=

我试过了

\/(?:.(?!\/.+\.))+$

但我不知道该怎么做。

最佳答案

一种选择可能是使用捕获组来匹配单词字符或连字符。您的匹配将位于第一个捕获组中。

^.*?\/([\w-]+)\.html

将匹配:

  • ^ 字符串开头
  • .*? 匹配除换行符以外的任意字符,非贪婪
  • \/ 匹配 /
  • ([\w-]+) 捕获组以匹配 1+ 次连字符的单词字符
  • \.html 匹配 .html

Regex demo

const regex = /^.*?\/([\w-]+)\.html/;
const str = `https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=`;
console.log(str.match(regex)[1]);

从最后一次出现的正斜杠开始匹配的另一个选项可能是匹配正斜杠并使用负前瞻来检查后面是否不再有正斜杠。然后使用捕获组来匹配非点:

\/(?!.*\/)([^.]+)\.html

Regex demo

const regex = /\/(?!.*\/)([^.]+)\.html/;
const str = `https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=`;
console.log(str.match(regex)[1]);

如果不使用正则表达式,您可以使用 dom 和 split:

const str = `https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=`;
let elm = document.createElement("a");
elm.href = str;
let part = elm.pathname.split('/').pop().split('.')[0];
console.log(part);

关于javascript - 如何使用正则表达式 javascript 获取最后一次出现的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790923/

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