6

For a URL such as this:

http://www.walmart.com/ip/0982724/some-text-here/234397280?foo=bar

How can I get a variable length number after the last slash?

I tried using this regex:

\/([0-9]+)

But it gets the first number, not the last one.

Demo: http://regex101.com/r/nU3wG2

I tried adding a dollar sign at the end, but then there were no matches.

Nate
  • 24,336
  • 33
  • 121
  • 207

3 Answers3

6

You can use this lookahead based regex:

\/([0-9]+)(?=[^\/]*$)

Online Demo: http://regex101.com/r/eL3mK3

This means find a number which is followed by 0 or more non-slash string till end.

anubhava
  • 713,503
  • 59
  • 514
  • 593
2

You can do it without a rarely implemented lookahead feature if you can work with contents of capturing groups.

\/([0-9]+)[^\/]*$

Online demo: http://regex101.com/r/yG2zN1

This means "find a slash followed with any positive number of digits followed with any non-slash characters followed with end of the line". As regexps find the longest leftmost match, all of those digits are captured into a group.

polkovnikov.ph
  • 5,806
  • 4
  • 42
  • 74
0
$aa = "http://www.walmart.com/ip/0982724/some-text-here/234397280?foo=bar";

$aa =~ /\/(\d+)\D+$/;

print $1, "\n";

This prints 234397280 \D is any non digit \d is any digit it is the same as '[0-9]

alexmac
  • 239
  • 2
  • 9
  • 1
    Anyone remember the tv show, name that tune? I can name that song in three notes etc... I can do that regular expression in 10 characters :) – alexmac Mar 11 '14 at 23:47