saintedlama
saintedlama

Reputation: 6898

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

admin/item/get

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

s.match(/.+?[\/$]/g)

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

Upvotes: 2

Views: 1038

Answers (3)

Manu K Mohan
Manu K Mohan

Reputation: 833

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

s.split("/");

["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.

s.match(/[^\/]+/g)

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

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173572

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:

s.match(/.+?(?:\/|$)/g)

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

As mentioned in the comments:

s.split('/')

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

Upvotes: 4

Anirudha
Anirudha

Reputation: 32797

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

It should be

.*?(?=\/|$)

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

[^/]*

Upvotes: 1

Related Questions