michalsol
michalsol

Reputation: 752

REGEX - specify groups, grouping order

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

Answers (1)

Sebastian Proske
Sebastian Proske

Reputation: 8413

There are basically two ways to achieve this:

  1. Lazy Matching - like /(.*?)/(.*)

.* 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.

  1. Negative character class matching - like /([^/]*)/(.*)

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

Related Questions