regexsplitregex-group

Split a string with key-value pairs if underscore in key


I've a string that has key value pairs with _ as their delimiter. The Problem is, there can be underscores within keys too.

What regex can I use to split these into key value pairs?

Intput:

C_OPS_CITY=SFO_C_OPS_SITE_INDICATOR=Office_IDENTITYCATEGORY=Employee_C_OPS_COMPANY=My Company_

Expected Output:

If not regex, what other logic can I use to split this string into array?


Solution

  • The values can be unambiguously identified only if they do not contain underscores. If that's indeed the case for you, you can then use a character set that excludes underscores to match values:

    [^=_][^=]*=[^_]+
    

    Demo: https://regex101.com/r/7W1WmX/4