Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for getting everything after last slash [duplicate]

Tags:

regex

I was browsing stackoverflow and have noticed a regular expression for matching everything after last slash is

([^/]+$) 

So for example if you have http://www.blah.com/blah/test The reg expression will extract 'test' without single quotes.

My question is why does it do it? Doesn't ^/ mean beginning of a slash?

EDIT: I guess I do not understand how +$ grabs "test". + repeats the previous item once or more so it ignores all data between all the / slashes. how does then $ extract the test

like image 630
CodeCrack Avatar asked Jan 20 '12 17:01

CodeCrack


People also ask

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

What is double slash in regex?

means, "match the 'period' as a literal character". If you don't have the backslash "escape character", the in most Regexp engines means, "match any character". Follow this answer to receive notifications.

How do I get everything in regular expressions?

Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.

What do forward slashes do in regex?

The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.


2 Answers

In original question, just a backslash is needed before slash, in this case regex will get everything after last slash in the string

([^\/]+$) 
like image 145
Behzad Avatar answered Nov 07 '22 13:11

Behzad


No, an ^ inside [] means negation.

[/] stands for 'any character in set [/]'.

[^/] stands for 'any character not in set [/]'.

like image 37
Dmitry Ovsyanko Avatar answered Nov 07 '22 14:11

Dmitry Ovsyanko