正则表达式,用于获取最后一个斜杠之后的所有内容

我在浏览 stackoverflow 时注意到一个正则表达式用于匹配上一个斜杠之后的所有内容

([^/]+$)

例如,如果你有一个“ href =”http://www.blah.com/bla/test“ > http://www.blah.com/blah/test Reg 表达式将提取没有单引号的“ test”。

我的问题是,它为什么这么做? 是不是意味着斜杠的开始?

编辑: 我想我不明白 + $如何抓住“测试”。+ 重复前一项一次或多次,因此忽略所有/斜杠之间的所有数据。那么 $如何提取测试

127143 次浏览

^ 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 /.

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.

No, an ^ inside [] means negation.

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

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

Within brackets, ^/ means NOT A /. So this is matching a sequence of non-/'s up to the end of the line.

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.

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

([^\/]+$)

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);