Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
Matt Coady Avatar asked Jan 10 '23 03:01

Matt Coady


1 Answers

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
like image 55
Anthony Forloney Avatar answered Jan 24 '23 12:01

Anthony Forloney