I'm having issues trying to come up with a regex in order to match a part of a path and then use the second capture group to extract it
let suppose that we have the following paths:
./var/lib/
var/lib/
./var/lib
from those examples that section of the string that I'm trying to match would be just (var/lib) for all those inputs, so I decided to try using a regex.
This is what I have so far:
(\.\/)?[A-Za-z0-9][A-Za-z0-9\/]+(\/)?$
So far it matches all the possible scenarios but it does not match the last capture group.
so for example ./var/lib/test/ is matched correctly, but the las / is not matched by the third capture group but for the second one and I cannot have that.
the correct behavior should be:
First group | Second Group | Third group |
---|---|---|
./ | var/lib/test | / |
You just need to use a lazy quantifier +?
instead of greedy +
(also, you missed second group in your original regex):
(\.\/)?([A-Za-z0-9][A-Za-z0-9\/]+?)(\/)?$
Lazy quantifier matches as little as possible, but since you require the match to include end of string with $
, it has no choice but to capture everything except possibly last /
.