Reputation: 752
When I write regex as follows:
/(.*)/(.*)
from string
/aaa/bbb/ccc
I get groups:
#1 aaa/bbb
#2 ccc
But I would like it to be like:
#1 aaa
#2 bbb/ccc
How can I change grouping order?
Upvotes: 0
Views: 116
Reputation: 8413
There are basically two ways to achieve this:
/(.*?)/(.*)
.*
matches greedy, so the first .*
first matches as much as possible (= the reminder of the string), then backtracks until the forward slash can be matched. Lazy matching works the other way around, .*?
matches as few as possible (= nothing) and then expands until the slash can be matched.
/([^/]*)/(.*)
As we know, that we want to match everything before the forward slash, we can use a character class where the forward slash is negated and then match greedy again. This is more performant as you can match in one step, instead expanding your pattern with lazy matching.
Upvotes: 2