Skip to content
Advertisement

Regex – split string with delimiters into groups

It’s needed to parse strings like:

  1. object/custom/name1/name2
  2. object/custom/name1/name2/typea
  3. 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)/ Match object/custom/ or object/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 either typea or typeb
    • (?:/(.*))? Optional non capture group, match / and capture in group 3 the rest of the line
  • )? Close non capture group and make it optional

Regex demo

Advertisement