[英]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})[^-]+/
正则表达式代码:
^
: 开始(?:[^\/]*\/){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.