Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capturing after the nth occurrence of a string using regex

My test string:

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

I am trying to capture the number in the string. The constants in that string are the the number is always preceded by 3 /‘s and followed by a -.

I am a regex noob and am struggling with this. I cobbled together (\/)(.*?)(-) and then figured I could get the last one programmatically, but I would really like to understand regex better and would love if someone could show me the regex to get the last occurrence of numbers between / and -.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use regexes if possible, i reccomend you to read – https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ blog post

To your question, its easier, faster, more bullet proof to get it using splits

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

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

// '51374'

hope it helps

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading