簡體   English   中英

如何使用正則表達式javascript獲取最后一次出現?

[英]How to get last occurrence with regex javascript?

您能幫我從字符串中提取“女士手表”嗎:

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

正則表達式演示

 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

正則表達式演示

 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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM