Regex does not match $ in character set


I'm currently fighting a weird javascript regex problem. I'm trying to match all characters between / or the end of input. For example this string


should be matched as:

[ 'admin', 'item', 'get' ]

I don't really care if / is part of the match or not, so this result would work for me too:

[ 'admin/', 'item/', 'get' ]

To match the input string s I'm using the regex


which results in

[ 'admin/', 'item/' ]

To my understanding the end of input $ is not matched in this character set.

When I try to match only the end of input using the regex s.match(/.+?$/g) I'm getting the expected result [ 'admin/item/get' ]. But placing the $ in a character set s.match(/.+?$/g) the match call returns null.

Any help appreciated...

Btw: I'm using node.js 0.8.20

Problem courtesy of: saintedlama


Because $ is treated as a character when placed inside a character set. This should do it though, it uses an alternation inside a non-memory capturing group and thus restores the meaning of $ to be the end-of-subject:


["admin/", "bla/", "bla"]

As mentioned in the comments:


["admin", "bla", "bla"]
Solution courtesy of: Ja͢ck


$ within character class [] has no special meaning and is treated as literal character

It should be


You can instead do dont have to check for / or $

Discussion courtesy of: Anirudha

You can attain the result using regex or split method for string object.

var s = "admin/item/get";

Using split method of string object.

Split the string by "/".


["admin", "item", "get"]

Using regex pattern.

Match the string with regular expression /[^\/]+/g, which matches all characters with occurence of one or more times except "/" character.


["admin", "item", "get"]
Discussion courtesy of: Manu K Mohan

This recipe can be found in it's original form on Stack Over Flow.