John Pangilinan
John Pangilinan

Reputation: 1031

Regex Group Slashes

I have a string:

/1/2/3/anystring as follows here even forward slashes/////

how can i capture the groups

(1) (2) (3) (anystring as follows here even forward slashes/////)

or conditionally if (2) or (3) cannot be captured then capture one (1) or (1)/(2) or (1)(2)(3) or all

i have tried

^/(.*)/(.*)/(.*)/(.*)

but it doesn't capture /1/2/ or /1/ or /1/2/3/.

Upvotes: 1

Views: 1089

Answers (3)

Bohemian
Bohemian

Reputation: 424983

Change your greedy quantifiers .* to reluctant quantifiers .*?:

^/(.*?)/(.*?)/(.*?)/(.*)

See live demo.

Upvotes: 1

fronthem
fronthem

Reputation: 4139

Try this

^(?:/(.*?))?(?:/(.*?))?(?:/(.*?)/).*/////

Just use quantifier ? which stands for quantity 0 or 1 and non-greedy quantifier *? to perform non-greedy match.

See: DEMO

Upvotes: 1

wwwy
wwwy

Reputation: 109

var str = "/1/2/3/anystring as follows here even forward slashes/////";
str.replace(/\/(([\w\s]|\/+$)+)/g,"($1)");

"(1)(2)(3)(anystring as follows here even forward slashes/////)"

Upvotes: 1

Related Questions