BeHFaR
BeHFaR

Reputation: 129

RegEx expression to split a string on comma with a condition in JavaScript

I'm very new to RegEx expressions and the problem is that I want to split a string with some conditions using RegEx. Let's say I want to split by comma, but if it's not followed by some certain things. The following example shows everything:

str = "a , b=10 , c=add(3,b) , d"
certainThings = ["add" , "sub"]

output of str.split(',') which splits only by comma is: ["a" , "b=10" , "c=add(3" , "b)" , "d"].

But I don't want to split on the 3rd comma as it's followed by one of the elements of the certainThings array.

The expected output is: ["a" , "b=10" , "c=add(3,b)" , "d"].

A possible solution might be to split by comma and concatenate two elements if the prior contains one elements of the certainThings array. But I think there should be a better way of doing this by RegEx expressions.

Upvotes: 3

Views: 3662

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21110

Instead of splitting on comma you could also select everything that is not a comma:

const str = "a , b=10 , c=add(3,b) , d";
const regex = /(?:\([^)]*\)|[^,])+/g;

console.log(
  str.match(regex).map(str => str.trim())
);

regex diagram

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

Assuming you only ever would have to worry about excluding commas inside singly-nested parentheses, we can try splitting on the following regex pattern:

\s*,\s*(?![^(]*\))

This says to split on comma, surrounded on both sides by optional whitespace, so long as we can't look forward and encounter a closing ) parenthesis without also first seeing an opening ( one. This logic rules out the comma inside c=add(3,b), because that particular comma hits a ) first without seeing the opening one (.

var str = "a , b=10 , c=add(3,b) , d"
parts = str.split(/\s*,\s*(?![^(]*\))/);
console.log(parts);

Upvotes: 3

Related Questions