簡體   English   中英

使用正則表達式在字符串第 n 次出現后捕獲

[英]Capturing after the nth occurrence of a string using regex

我的測試字符串:

/custom-heads/food-drinks/51374-easter-bunny-cake

我正在嘗試捕獲字符串中的數字。 該字符串中的常量是數字始終以 3 /開頭並后跟-

我是一個正則表達式新手,正在為此苦苦掙扎。 我拼湊(\/)(.*?)(-)然后想我可以通過編程方式獲得最后一個,但我真的很想更好地理解正則表達式並且如果有人可以向我展示正則表達式以獲得最后一次出現我會很高興/-之間的數字。

盡可能不要使用正則表達式,我建議您閱讀 - https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/博客文章

對於您的問題,使用拆分更容易、更快、更防彈

const articleName = "/custom-heads/food-drinks/51374-easter-bunny-cake".split("/")[3]
// '51374-easter-bunny-cake'

const articleId = articleName.split("-")[0]

// '51374'

希望能幫助到你

您可以將此正則表達式與捕獲組一起使用:

^(?:[^\/]*\/){3}([^-]+)

或者在現代瀏覽器中,您可以使用后向斷言:

/(?<=^(?:[^\/]*\/){3})[^-]+/

正則表達式演示 1

正則表達式演示 2

正則表達式代碼:

  • ^ : 開始
  • (?:[^\/]*\/){3} :匹配 0 個或多個非/字符后跟/ 重復此組3次
  • ([^-]+) :匹配 1+ 個非連字符

代碼:

 const s = `/custom-heads/food-drinks/51374-easter-bunny-cake`; const re = /^(?:[^\/]*\/){3}([^-]+)/; console.log (s.match(re)[1]);

利用

 const str = `/custom-heads/food-drinks/51374-easter-bunny-cake` const p = /(?:\/[^\/]*){2}\/(\d+)-/ console.log(str.match(p)?.[1])

請參閱正則表達式證明

解釋

Non-capturing group (?:\/[^\/]*){2}
{2} matches the previous token exactly 2 times
\/ matches the character / with index 4710 (2F16 or 578) literally (case sensitive)
  Match a single character not present in the list below [^\/]
  * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  \/ matches the character / with index 4710 (2F16 or 578) literally (case sensitive)
\/ matches the character / with index 4710 (2F16 or 578) literally (case sensitive)
1st Capturing Group (\d+)
  \d matches a digit (equivalent to [0-9])
  + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)

暫無
暫無

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

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