Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 725
BeHFaR Avatar asked Dec 18 '25 07:12

BeHFaR


1 Answers

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);
like image 92
Tim Biegeleisen Avatar answered Dec 20 '25 22:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!