How to pick a number in the middle of a string

Asked

Viewed 84 times

0

I’m trying to get a number inside a url https://pokeapi.co/api/v2/ability/35/ This number may vary from 1 4 digits ago. I want to catch the number 35 but with my current regex I’m catching the 2 + 35 (235) follow the regex I’m using:
/[^\d]/g
This url has no other variation

  • 2

    Depending on the language there are more appropriate functions for url handling

  • Does the number need to have two digits? Or does it need to be between bars? Well, from your statement (number inside string), it seems correct to take 2 and 35.

  • Could [Edit] and put the tool or language you are using? And if it is a language (seems to be Javascript, but please confirm), also put the code you used, because [^\d] takes everything that nay is digit, see: https://regex101.com/r/GZ0TYq/1 - that being said, is the tip of the comment above: all languages have some form of URL manipulation, which is much better than using regex

  • It would also be interesting to put all the rules: the number is always at the end of the URL? How many digits? Can they have other digits (besides v2) in other parts? Is it to get them too? etc...

  • Yes I am using javascript. And the number I need is only the 35 I can even treat that data to take the 2 from the beginning but I wanted to save lines of code. 35 can range from 1 numbers there are up to a 4 digits.

  • In case I only need the final number there is no number beyond the end and v2

Show 1 more comment

2 answers

3

You can use the function split for that purpose.

This function will split the string into an array, given a certain separator.

var url = 'https://pokeapi.co/api/v2/ability/35/';
var pathArray = url.split('/');
console.log(pathArray[6]);

0


The regex below identifies all strings composed by digits of 0 to 9 1 to 4 characters long, surrounded by bars (/).

/(?<=\/)\d{1,4}(?=\/)/g

In this way, the digits of alphanumeric parts, such as the 2 of v2.

Check online.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.