Regular expression to parse url

Merc

I am trying to get a regular expression in Javascript where:

/something/:workspaceId/somethingelse/:userId/blah/:id

Is parsed so that I get an array with ['workspaceId', 'userId', 'id'].

Initial test:

p.match(/:.*?\/+/g )

This only matches the first two, workspaceId and userId.

This feels like a bit of a hack:

(p + '/').match(/:.*?\/+/g )

And it still returns :workspaceId rather than workspaceId.

Trying to fix it with whatI think the brackets should be for:

(p + '/').match(/:(.*)?\/+/g )

This last one really ought to work, but won't (since there are brackets, I expect the regexp only to return the match in the brackets).

At the moment, I am doing:

r = (p + '/').match(/:.*?\/+/g).map( function(i){return i.substr(1, i.length - 2 )  } );

But I would love to get something that:

1) Doesn't add that '/' at the end (although I could live with it)

2) It doesn't use the expensive map() method to do something the regexp should be doing in the first place

Bryan Elliott

you could use a look ahead assertion regex for this, like so:

(?=:):(.*?)(?=\/|$)

working example:

http://regex101.com/r/gO7nO0

Matches:

MATCH 1
1.  
`workspaceId`
MATCH 2
1.  
`userId`
MATCH 3
1.  
`id`

Or better yet, you could simplify and just use:

:(\w+)

working example:

http://regex101.com/r/nG4mI2

Matches:

MATCH 1
1.  
`workspaceId`
MATCH 2
1.  
`userId`
MATCH 3
1.  
`id`

Edit:

Here is a working pure javascript example:

http://jsfiddle.net/BkbrF/2/

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related