Home > Software engineering >  Matching everything except a specific series of characters to split a string
Matching everything except a specific series of characters to split a string

Time:01-19

I have a process that some data goes through that can split a field into multiple values, using Regex.

The current regex is: [^,\s][^,][^,\s]

An example string that it would split would be this:

0/Books,1/Books/Fiction,2/Books/Fiction/Sci-Fi

The output would be an array of values: "0/Books","1/Books/Fiction","2/Books/Fiction/Sci-Fi"

It works great except when there is a comma in the values.

i.e. 0/Books, Magazines and Others/, 1/Books, Magazines and Others/Fiction/, 2/Books, Magazines and Others/Fiction/Sci-Fi/

Since my regex is splitting in a single character, it's splitting at each comma. Instead, I want it to split at "/, " (forward slash, comma, space).

I cannot figure out how to do that.

Any thoughts?

CodePudding user response:

If you want to split on /, or on a single comma:

\/,\s|,

Regex demo

Or else split on only \/\s without the alternation.

  •  Tags:  
  • Related