Matt Coady
Matt Coady

Reputation: 3856

Regex - Extract digits from a url

I have this url:

http://example.com/things/stuff/532453?morethings&stuff=things&ver=1

I need just that number in the middle there. Closest I got was

(\d*)?\?

but this includes the question mark. Basiclly all numbers that come before the ? all the way to the slash so the ouput is 532453.

Upvotes: 5

Views: 6312

Answers (3)

vjdhama
vjdhama

Reputation: 5078

Try this :

url = "http://example.com/things/stuff/532453?morethings&stuff=things"
number  = url.match(/(\d+)\?/g)[0].slice(0,-1)

Though the approach is slightly naive, it works. It grabs numbers with ? at the end then removes the ? from the end using slice.

Upvotes: 0

Anthony Forloney
Anthony Forloney

Reputation: 91816

Try the following regex (?!\/)\d+(?=\?):

url = "http://example.com/things/stuff/532453?morethings&stuff=things"
url.match(/(?!\/)\d+(?=\?)/) # outputs 532453

This regex will attempt to match any series of digits only after a / and before ? by using negative/positive lookahead without returning the / or ? as part of the match.

A quick test within developer tools:

# create a list of example urls to test against (only one should match regex)
urls = ["http://example.com/things/stuff/532453?morethings&stuff=things", 
        "http://example.com/things/stuff?morethings&stuff=things",        
        "http://example.com/things/stuff/123a?morethings&stuff=things"]

urls.forEach(function(value) {
                 console.log(value.match(/(?!\/)\d+(?=\?)/)); 
             })

# returns the following:
["532453"]
null
null

Upvotes: 7

Luc
Luc

Reputation: 2805

Just use this:

([\d]+)

You can check this link out: https://regex101.com/r/hR2eY7/1

if you use javascript:

/([\d]+)/g

Upvotes: 2

Related Questions