Search code examples
regexadobe-analytics

Regex: Split string of varying length into multiple groups without using supporting code


  • I have a string that can vary in size containing multiple substrings
  • These substrings are delimited by a colon.
  • I need to capture these substrings into groups, but I cannot use any supporting language to do this. It has to be regex only and work in this tester https://regexr.com/. The reason for this limitation is that I am cutting strings via a UI that doesn't support additional code (Adobe Analytics). This means I cannot use functions such as 'split()' or 'explode()'.
  • I would like a single expression as an answer.

Example1: test1:test2:test3:test4 would be broken into 4 groups.

  1. test1
  2. test2
  3. test3
  4. test4

Example2: 123:abc would be broken into just 2 groups.

  1. 123
  2. abc

Is this possible? Thanks, Chris


Solution

  • Yes, quite simple actually:

    /([^:]+)/ 
    

    I hope that is what you meant :)

    UPDATE

    After you refined your answer, you mean you want multiple groups on one match. This is contrary to how you would normally use a regex (and you are probably aware of that), but with the given limitations of your tool, the best you can do is a finite set of groups, which you have to read from your first match.

    I am not familiar with the tool you use, so I can't say for sure if it won't produce any negative side-effects, but this would be the closest you could get. Example for maximum of 8 groups:

    ([^:]+)?:?([^:]+)?:?([^:]+)?:?([^:]+)?:?([^:]+)?:?([^:]+)?:?([^:]+)?:?([^:]+)?
    

    A proper solution that deals with indefinite groups would not work unfortunately. You need to manually create matching groups. Simply duplicate the following for as many groups as you need (max):

    ([^:]+)?:?
    

    It is ugly but might just work.

    If you need this completely dynamic, however, that is not possible.