It’s needed to parse strings like:
object/custom/name1/name2
object/custom/name1/name2/typea
object/custom/name1/name2/typea/item
The result I’m expected to get is:
group1: name1/name2
group2: typea
group3: item
Only group1
(the group with name) is required. Other groups (2,3) are optional. It depends on the string. E.g. for the first string should be present only first group with the string name1/name2
.
The string typea
is static strings.
Here is the link with the playground: https://regex101.com/r/j1ay1s/1/
Or regex: object/(custom|standard)/(.*)(?:/(typea|typeb))(?:/(.*))?
Advertisement
Answer
You could get 3 capturing groups making the second and third optional, use a character class for type[ab]
and don’t use a capturing group for (custom|standard)
object/(?:custom|standard)/(.*?(?=/type[ab]|$))(?:/(type[ab])(?:/(.*))?)?
Explanation
object/(?:custom|standard)/
Matchobject/custom/
orobject/standard/
(.*?(?=/type[ab]|$))
Caputure in group 1 as least as possible characters until you encounter typea or typeb or the end of the string(?:
Non capture group/(type[ab])
Match/
and capture in group 2 eithertypea
ortypeb
(?:/(.*))?
Optional non capture group, match/
and capture in group 3 the rest of the line
)?
Close non capture group and make it optional