Regular Expression for getting everything after last slash
RegexRegex Problem Overview
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
Regex Solutions
Solution 1 - Regex
In original question, just a backslash
is needed before slash
, in this case regex will get everything after last slash
in the string
([^\/]+$)
Solution 2 - Regex
No, an ^
inside []
means negation.
[/]
stands for 'any character in set [/]'.
[^/]
stands for 'any character not in set [/]'.
Solution 3 - Regex
Just fyi, for a non-regex version of this, depending on the language you're in, you could use a combination of the substring and lastIndexOf methods. Just find the last index of the "/" character, and get the substring just after it.
i.e., in Java
String targetString = "a/string/with/slashes/in/it";
int lastSlashIndex = targetString.lastIndexOf('/');
String everythingAfterTheFinalSlash = targetString.substring(lastSlashIndex + 1);
Solution 4 - Regex
Within brackets, ^/ means NOT A /. So this is matching a sequence of non-/'s up to the end of the line.
Solution 5 - Regex
^
at the start of []
is character class negation. [...]
specifies a set of characters to match. [^...]
means match every character except that set of characters.
So [^/]
means match every possible character except /
.
Solution 6 - Regex
if you put the ^ in a group it says all charters not in this group. So match all charter that are not slashes until the end of line $ anchor.
Solution 7 - Regex
No, the ^
means different things depending on context. When inside a character class (the []
), the ^
negates the expression, meaning "match anything except /
.
Outside of []
, the ^
means what you just said.