Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number after last slash using regex?

Tags:

regex

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.

like image 323
Nate Avatar asked Mar 11 '14 23:03

Nate


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

How do you end a line in regex?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

How do I check a number in regex?

The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.


2 Answers

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.

like image 101
anubhava Avatar answered Nov 15 '22 06:11

anubhava


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.

like image 43
polkovnikov.ph Avatar answered Nov 15 '22 08:11

polkovnikov.ph