使用正则表达式在字符串第n次出现后捕获



我的测试字符串:

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

我正试图捕捉字符串中的数字。该字符串中的常量是数字。数字前面总是3个/,后面是一个-

我是一个正则表达式noob,正在与此作斗争。我拼凑了(/)(.*?)(-),然后想我可以通过编程获得最后一个,但我真的很想更好地理解正则表达式,如果有人能给我看正则表达式,以获得/-之间最后一个数字。

如果可能的话,不要使用正则表达式,我建议您阅读-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}([^-]+)

或者在现代浏览器中,您可以使用lookbacking断言:

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

RegEx Demo 1

RegEx Demo 2

RegEx代码:

  • ^:启动
  • (?:[^/]*/){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)

最新更新